Functions are first-class objects in R. Define with function(). The last evaluated expression is returned implicitly, or use return() explicitly. Default argument values are set in the signature. Functions can be anonymous (lambda-style).
# Simple function
square <- function(x) {
x^2
}
square(4) # 16
# With default argument
greet <- function(name, greeting = "Hello") {
paste(greeting, name)
}
greet("Aurèle") # "Hello Aurèle"
greet("Aurèle", "Salut") # "Salut Aurèle"
# Multiple return values (via list)
summary_stats <- function(x) {
list(mean = mean(x, na.rm = TRUE),
sd = sd(x, na.rm = TRUE),
n = sum(!is.na(x)))
}
res <- summary_stats(c(1, 2, NA, 4, 5))
res$mean # 3
res$n # 4
# Anonymous function (R 4.1+ shorthand)
(\ (x) x^2)(5) # 25