r - Apply list of functions to list of values -
in reference this question, trying figure out simplest way apply list of functions list of values. basically, nested lapply
. example, here apply sd
, mean
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 hoping avoid inner function
, have like:
sapply(funs, sapply, x=trees)
which doesn't work because x
matches first sapply
instead of second. can functional::curry
:
sapply(funs, curry(sapply, x=trees))
but hoping maybe there clever way positional , name matching i'm missing.
since mapply
use ellipsis ...
pass vectors (atomics or lists) , not named argument (x) in sapply, lapply, etc ...
don't need name parameter x = trees
if 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 1 letter close looking ! :)
note used list funs
because can't create dataframe of functions, got error.
> r.version.string [1] "r version 3.1.3 (2015-03-09)"
Comments
Post a Comment