R
Beginner
1 min read
Defining and Calling Functions
Example
# Basic function definition
greet <- function(name, greeting = "Hello") {
paste(greeting, name)
}
greet("Alice") # "Hello Alice"
greet("Bob", "Hi") # "Hi Bob"
greet(greeting = "Hey", name = "Carol") # named args, any order
# Last-expression return (no explicit return() needed)
square <- function(x) x ^ 2
square(7) # 49
# Explicit return for early exit
safe_log <- function(x) {
if (x <= 0) return(NA)
log(x)
}
safe_log(-1) # NA
safe_log(10) # 2.302585
# Variadic functions with ...
my_paste <- function(..., sep = " ") {
args <- list(...)
paste(args, collapse = sep)
}
my_paste("one", "two", "three", sep = "-") # "one-two-three"
# Passing ... to another function
loud_mean <- function(x, ...) {
result <- mean(x, ...)
cat("Mean is:", result, "\n")
invisible(result)
}
loud_mean(c(1, 2, NA), na.rm = TRUE) # Mean is: 1.5
# Closures: function factories
make_power <- function(exp) {
function(x) x ^ exp # captures 'exp' from enclosing env
}
square <- make_power(2)
cube <- make_power(3)
square(4) # 16
cube(3) # 27
# Anonymous functions (lambda-style)
(function(x, y) x + y)(5, 3) # 8
sapply(1:5, function(x) x * x) # 1 4 9 16 25