Sarang Manjrekar
Sarang Manjrekar

Reputation: 1991

Using R functions as a list

I am creating an R list comprising of few functions as :

funs <- list(
+     sum = sum,
+     mean = mean,
+     median = median
+     )

In order to use lapply, the Hadley Wickham's book that i am referring to uses :

lapply(funs, function(f) f(x))

I do get the first argument of lapply function is list, but how come function(f) f(x) serves to be the the second argument of lapply, which should be a function ideally. My x is:

x <- 1:10

Upvotes: 2

Views: 57

Answers (2)

Harald Gliebe
Harald Gliebe

Reputation: 7564

Maybe it gets clearer when you assign the anonymous function to a name g

g <- function(f) { 
  f(x)
}

g has a function as parameter and will call this function with the argument x, that is obtained from the lexical scope. So for x <- 1:10 you get

g(sum) # = sum(x) = sum(1:10) 
[1] 55

And similarly

lapply(funs, g) # = list(g(sum), g(means), g(median)
                # = list(sum(x), means(x), median(x)
                # = list(sum(1:10), means(1:10), median(1:10)
$sum
[1] 55

$mean
[1] 5.5

$median
[1] 5.5

Upvotes: 3

Hong Ooi
Hong Ooi

Reputation: 57686

The second argument to lapply is

function(f) f(x)

which is a function. It's a function whose argument is also a function, f.

To elucidate what's happening, let's take out the "anonymous" from anonymous function:

getFunc <- function(f) f(x)
lapply(funs, getFunc)

This is exactly the same as

lapply(funs, function(f) f(x))

without having to define getFunc separately.

Going further, let's take out the x:

getFunc <- function(f, xx) f(xx)
lapply(funs, getFunc, xx=x)

This is the same as

lapply(funs, function(f) f(x))

but explicitly passing in the numbers on which to compute the sum, mean and median, rather than automagically getting them from the global environment.

Upvotes: 3

Related Questions