← Back to R Course | Chapter 5: Functions | Lesson 6 of 7

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:

  1. Anonymous Functions
Syntax
r
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

markup
numbers <- c(1, 2, 3, 4)

squared <- sapply(numbers, function(x) x * x)
print(squared)

doubled <- sapply(numbers, \(x) x * 2)
print(doubled)
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
  1. Writing function(x) x * x without passing it to something, and expecting it to run by itself.
  2. Using the \(x) shorthand on R versions before 4.1, where it is a syntax error.
  3. Forgetting that sapply returns 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.