Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are anonymous functions in R?



Most functions in R are named functions where a variable (or name) is assigned to the function. The name or variable is used to invoke the function.


The syntax of the named function is as follows:

fname <- function(arg_1, arg_2, ...) {
            Function body

where fname is the name of the function and arg_1, arg_2 are the function arguments.

Code example

In the code below, we define a function add_func that takes two parameters and returns the sum.

add_func <- function(x, y) {
     x + y

Anonymous functions

Functions without a variable name are known as anonymous functions. These functions, which are also referred to as lambda functions, are created temporarily and are utilized without having a variable name assigned to them.

The syntax for writing a named function and an anonymous function is similar. The only difference is that we don’t designate a variable to the function.

We define an anonymous function that is passed to the mapply() function.

a = c(5, 9, 2, 2)
b = c(1, 3, 6, 9)
c = c(4, 4, 4, 4)

mapply(function(a, b, c) { a*b + c }, a, b, c)

An anonymous function can be invoked on its own:

(function(x) x + x)(3)



View all Courses

Keep Exploring