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.
Use the map() Function to Apply a Function to a List in Python. The map() function is used to apply a function to all elements of a specific iterable object like a list, tuple, and more. It returns a map type object which can be converted to a list afterward using the list() function.
lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.
sapply() function in R Language takes list, vector or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of same length of original set.
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 funs
because I can't create a dataframe of functions, I got an error.
> R.version.string [1] "R version 3.1.3 (2015-03-09)"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With