R Language Anonymous functions


Example

An anonymous function is, as the name implies, not assigned a name. This can be useful when the function is a part of a larger operation, but in itself does not take much place. One frequent use-case for anonymous functions is within the *apply family of Base functions.

Calculate the root mean square for each column in a data.frame:

df <- data.frame(first=5:9, second=(0:4)^2, third=-1:3)

apply(df, 2, function(x) { sqrt(sum(x^2)) })
    first    second     third 
15.968719 18.814888  3.872983 

Create a sequence of step-length one from the smallest to the largest value for each row in a matrix.

x <- sample(1:6, 12, replace=TRUE)
mat <- matrix(x, nrow=3)

apply(mat, 1, function(x) { seq(min(x), max(x)) })

An anonymous function can also stand on its own:

(function() { 1 })()
[1] 1

is equivalent to

f <- function() { 1 })
f()
[1] 1