0
0
R Programmingprogramming~5 mins

Anonymous functions in R Programming

Choose your learning style9 modes available
Introduction

Anonymous functions let you create quick, unnamed functions to use right away without giving them a name.

When you want to apply a simple operation inside another function without naming it.
When you need a small function just once, like in sorting or filtering data.
When you want to keep your code short and clear by avoiding extra function names.
Syntax
R Programming
function(arguments) {
  # code here
}

Anonymous functions are created using the function keyword without assigning a name.

You can pass them directly as arguments to other functions.

Examples
A simple anonymous function that adds 1 to its input.
R Programming
function(x) { x + 1 }
Using an anonymous function inside sapply to double each number in a vector.
R Programming
sapply(1:5, function(x) { x * 2 })
Anonymous function to square each element in a list.
R Programming
lapply(list(1, 2, 3), function(x) { x^2 })
Sample Program

This program adds 10 to each number in the vector numbers using an anonymous function inside sapply.

R Programming
numbers <- 1:5
result <- sapply(numbers, function(x) { x + 10 })
print(result)
OutputSuccess
Important Notes

Anonymous functions are useful for quick tasks but can be harder to debug if complex.

Keep anonymous functions simple and short for better readability.

Summary

Anonymous functions are unnamed functions created on the spot.

They are handy for quick, simple operations inside other functions.

Use them to keep code concise and avoid cluttering with many function names.