Functions let you package up a piece of logic so you can reuse it without rewriting it. In R, you create functions with the function() keyword. They can take inputs (parameters) and send back a result. The beauty is that once you've written a function, you can call it from anywhere in your script.
Defining a Function
Use function followed by parentheses for parameters and curly braces for the body. R returns the last expression automatically โ but you can also use return() to be explicit.
# Simple function โ last expression is returned
square <- function(x) {
x * x
}
square(5)
# Function with return() explicitly
greet <- function(name) {
return(paste("Hello,", name))
}
greet("Alice")
Try it Yourself โ
Multiple Parameters
You can pass multiple arguments. R matches them by position or by name. Default values make parameters optional.
add <- function(a, b = 0) {
a + b
}
add(3, 4)
add(3) # uses default b = 0
Try it Yourself โ
Functions That Return Nothing
Sometimes you want a function to do something โ like print a message โ without returning a value. That's fine too. Invisible NULL is returned by default.
show_info <- function(name, age) {
cat(name, "is", age, "years old.\n")
}
show_info("Bob", 28)
Try it Yourself โ