Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply list of functions to list of values

Tags:

r

apply

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.

like image 423
BrodieG Avatar asked Jun 10 '15 14:06

BrodieG


People also ask

How do I apply a function to all elements in a list?

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.

How do I apply a function to a list in R?

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.

What is Sapply?

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.


1 Answers

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)" 
like image 175
Julien Navarre Avatar answered Sep 18 '22 20:09

Julien Navarre