Anonymous Functions

Here is an example of an anonymous function. It generates a vector of values but the function is not allocated a name (although the answer could be).

(function(x,y){ z <- 2*x^2 + y^2; x+y+z })(0:7, 1)

[1]  2  5  12  23  38  57  8 0  107

The function first uses the supplied values of x and y to calculate z, then returns the value of x + y + z evaluated for eight values of x (from 0 to 7) and one value of y (1). Anonymous functions are used most frequently with apply, sapply and lapply (p. 68).

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.