Skip to content
R

Functions

Define functions with defaults, variadic args, closures, and higher-order use.

#function#closure

Code

r
# Basic function
square <- function(x) x^2
print(square(5))

# Default arguments
greet <- function(name = "world", greeting = "Hello") {
  paste(greeting, name, sep = ", ")
}
print(greet())
print(greet("Alice"))
print(greet("Bob", "Hi"))

# Named and partial matching
f <- function(a, b, c) a + b + c
print(f(c = 3, 1, 2))

# Variable arguments
concat <- function(..., sep = " ") {
  paste(..., sep = sep)
}
print(concat("a", "b", "c"))
print(concat("a", "b", "c", sep = "-"))

# Return value (last expression or explicit)
sign_num <- function(x) {
  if (x > 0) return("positive")
  if (x < 0) return("negative")
  "zero"
}
print(sign_num(-3))

# Closures
counter <- function() {
  n <- 0
  list(
    inc = function() { n <<- n + 1; n },
    get = function() n
  )
}
cnt <- counter()
print(cnt$inc())
print(cnt$inc())
print(cnt$get())

# Anonymous functions in sapply
print(sapply(1:5, function(n) n^3))

# Function as argument
apply_twice <- function(f, x) f(f(x))
print(apply_twice(function(x) x + 1, 5))