Write an R function called multiply that takes two arguments x and y and returns their product. Then call the function with x = 4 and y = 7.
Functions allow you to group code into reusable blocks. They help make your code cleaner and easier to maintain.
Use the function()
keyword to define a function.
greet <- function(name) {
message <- paste("Hello,", name, "!")
return(message)
}
print(greet("Alice"))
Functions can take multiple arguments.
add_numbers <- function(a, b) {
return(a + b)
}
print(add_numbers(5, 3))
A function can return a value using return()
, or implicitly return the last evaluated expression.
add_numbers <- function(a, b) {
return(a + b)
}
print(add_numbers(5, 3))
Functions make it easier to write modular, readable, and reusable R code.