Anonymous Functions
An anonymous function is a small helper with no name, like a quick note you pass to a friend and then throw away. It is handy when another function needs a short instruction.
In this page:
Syntax
function(x) expression
(function(x) expression)(value)
sapply(vector_name, function(x) expression)
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Writing
function(x) x * xwithout passing it to something, and expecting it to run by itself. - Using the
\(x)shorthand on R versions before 4.1, where it is a syntax error. - Forgetting that
sapplyreturns a vector but can return a list when results differ in length.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: