Anonymous Functions
In this page:
Anonymous Functions
R lets you define a function without naming it, useful when passing a short function directly as an argument to another function, like sapply(). Since R 4.1, the compact \(x) x * 2 syntax is a shorthand for function(x) x * 2. Anonymous functions keep short, one-off logic inline instead of requiring a separate named definition.
Note: The backslash shorthand \(x) ... (R 4.1+) is a more concise alternative to writing function(x) ... for short anonymous functions.
Example: Anonymous Functions
numbers <- c(1, 2, 3, 4)
squared <- sapply(numbers, function(x) x * x)
print(squared)
doubled <- sapply(numbers, \(x) x * 2)
print(doubled)
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: