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

Anonymous Functions

In this page:

  1. Anonymous Functions

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)
🔒

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.