Introduction
Functions help keep your code neat and easy to understand by grouping related steps together.
Functions help keep your code neat and easy to understand by grouping related steps together.
function_name <- function(arguments) {
# code to run
return(value)
}Use function_name to name your function clearly.
Arguments are inputs your function needs to work.
say_hello <- function() {
print("Hello!")
}add_two <- function(x) {
return(x + 2)
}This program defines a function to greet someone by name, then calls it twice with different names.
greet <- function(name) {
message <- paste("Hello," , name)
print(message)
}
greet("Alice")
greet("Bob")Functions make your code easier to fix and improve later.
Try to give functions clear names that say what they do.
Functions group code to keep it organized.
They help you reuse code without copying it.
Functions make your programs easier to read and test.
greet in R?greet as a function that prints "Hello".add <- function(x, y) {
return(x + y)
}
result <- add(3, 4)
print(result)add takes two inputs and returns their sum.add(3, 4) returns 3 + 4 = 7, which is stored in result and printed.multiply <- function(x, y) {
product = x * y
return product
}return must be followed by parentheses enclosing the value to return.return product without parentheses, which causes a syntax error.Pass the test and this pattern moves unknown