R Anonymous Functions
An anonymous function is a function without a name. You define it and use it immediately without storing it in a variable. Anonymous functions are useful when you need a short, one-time function — especially when passing a function as an argument to another function like lapply(), sapply(), or Map().
Regular Function vs Anonymous Function
# Regular (named) function square <- function(x) x^2 square(5) # 25 # Anonymous function — define and use immediately (function(x) x^2)(5) # 25 # Anonymous function passed to sapply sapply(1:5, function(x) x^2) # [1] 1 4 9 16 25
The New Shorthand Syntax (R 4.1+)
# Old syntax sapply(1:5, function(x) x^2) # New shorthand: \(x) instead of function(x) sapply(1:5, \(x) x^2) # Both produce: 1 4 9 16 25
With lapply
prices <- list(100, 250, 175, 320) # Apply 10% discount to each price discounted <- lapply(prices, function(p) p * 0.90) unlist(discounted) # 90 225 157.5 288
With sapply
students <- list( list(name="Asha", scores=c(80,85,90)), list(name="Balu", scores=c(70,75,80)), list(name="Cena", scores=c(90,95,92)) ) # Get average score for each student sapply(students, function(s) mean(s$scores)) # [1] 85.00 75.00 92.33
With Map()
lengths <- c(5, 8, 3) widths <- c(4, 2, 6) # Calculate area for each length-width pair areas <- Map(function(l, w) l * w, lengths, widths) unlist(areas) # 20 16 18
With Pipe Operator
# Chain with native pipe c(1, 4, 9, 16, 25) |> (\(x) x[x > 5])() # 9 16 25 # Or with dplyr library(dplyr) data.frame(x = 1:5) |> mutate(y = (\(v) v^2)(x))
Immediately Invoked Function Expression (IIFE)
# Define and call in one expression — wrapping in () is required
result <- (function(a, b) {
cat("Computing", a, "+", b, "\n")
a + b
})(10, 20)
# result = 30
When to Use Anonymous Functions
Use Anonymous When: Use Named When: ────────────────────────────────── ────────────────────────────── Short, one-time logic Used in multiple places Passed directly to apply functions Needs testing/documentation Simple transformation in a pipeline Complex multi-step logic
Practical: Data Transformation Pipeline
raw_scores <- c(55, 78, 43, 91, 62, 80) processed <- raw_scores |> (\(x) x[x >= 50])() |> # filter: keep >=50 only (\(x) x / max(x) * 100)() |> # normalize to 0-100 (\(x) round(x, 1))() # round to 1 decimal print(processed) # 60.4 85.7 100.0 68.1 87.9
Anonymous functions keep your code clean when you need a quick, single-use transformation. The \(x) shorthand introduced in R 4.1 makes them even more compact. You will use them constantly with lapply(), sapply(), Map(), and pipe operations in data analysis workflows.
