Functions
Define functions with defaults, variadic args, closures, and higher-order use.
Code
# 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))Explanation
R functions are first-class objects: they can be assigned, passed as arguments, and returned from other functions. Default arguments, named calls, and the dots (...) let you write flexible APIs. Closures capture their enclosing environment, allowing stateful factories like the counter example using the <<- super-assignment operator.
More R Snippets
Data Frames
Create, inspect, filter, mutate, sort, aggregate, and merge data frames.
Vectors
Build atomic vectors, apply vectorized ops, index, and recycle.
ggplot2
Build layered plots with geoms, facets, and themes using the grammar of graphics.
dplyr
Chain mutate, filter, group_by, summarise, and joins with the native pipe.
Statistics
Compute summaries, run t-tests, linear models, ANOVA, and use distributions.
Apply Family
Apply functions over arrays, lists, and groups with apply, lapply, sapply, tapply.