BrodieG BrodieG - 3 months ago 13
R Question

Apply list of functions to list of values

In reference to this question, I was trying to figure out the simplest way to apply a list of functions to a list of values. Basically, a nested

lapply
. For example, here we apply
sd
and
mean
to built in data set
trees
:

funs <- list(sd=sd, mean=mean)
sapply(funs, function(x) sapply(trees, x))


to get:

sd mean
Girth 3.138139 13.24839
Height 6.371813 76.00000
Volume 16.437846 30.17097


But I was hoping to avoid the inner
function
and have something like:

sapply(funs, sapply, X=trees)


which doesn't work because
X
matches the first
sapply
instead of the second. We can do it with
functional::Curry
:

sapply(funs, Curry(sapply, X=trees))


but I was hoping maybe there was a clever way to do this with positional and name matching that I'm missing.

Answer

Since mapply use ellipsis ... to pass vectors (atomics or lists) and not a named argument (X) as in sapply, lapply, etc ... you don't need to name the parameter X = trees if you use mapply instead of sapply :

funs <- list(sd = sd, mean = mean)

x <- sapply(funs, function(x) sapply(trees, x))

y <- sapply(funs, mapply, trees)

> y
              sd     mean
Girth   3.138139 13.24839
Height  6.371813 76.00000
Volume 16.437846 30.17097
> identical(x, y)
[1] TRUE

You were one letter close to get what you were looking for ! :)

Note that I used a list for funsbecause I can't create a dataframe of functions, I got an error.

> R.version.string
[1] "R version 3.1.3 (2015-03-09)"