Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: apply list of functions on list of argument by name

Tags:

r

Someone has solved my question applying list of functions on list of argument by order, now I have another similar question, how to apply function in the list my name? For example, if I have:

f1 <- function(x) {x}
f2 <- function(x) {2*x}
f3 <- function(x) {3*x}
fun_list <- list(good=f1, better=f2, best=f3)
arg_list <- list(better=1, best=2, good=3)

I want to get the list of functions called on their respective named parameter, i.e., I want:

some_magic_fun(fun_list, arg_list) == list(f1(3), f2(1), f3(2)) 

What would be good way to do it?

like image 545
user3684014 Avatar asked Aug 19 '14 21:08

user3684014


People also ask

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 does apply () do in R?

The apply() function lets us apply a function to the rows or columns of a matrix or data frame. This function takes matrix or data frame as an argument along with function and whether it has to be applied by row or column and returns the result in the form of a vector or array or list of values obtained.

Can functions take another function as an argument in R?

14.1 Functions in RFunctions can be passed as arguments to other functions. This is very handy for the various apply functions, like lapply() and sapply() . Functions can be nested, so that you can define a function inside of another function.

Can a list contain a list in R?

The list data structure in R allows the user to store homogeneous (of the same type) or heterogeneous (of different types) R objects. Therefore, a list can contain objects of any type including lists themselves.


2 Answers

As I understand it you want to choose the functions and the arguments from lists not necessarily in order but that have a common set of names:

 lapply(names(fun_list), function(n) fun_list[[n]](arg_list[[n]]) )
#----------
[[1]]
[1] 3

[[2]]
[1] 2

[[3]]
[1] 6

It wasn't entirely clear if you want the results but that was what I assumed. If you really wanted unevaluated expressions, you will need to clarify.

like image 143
IRTFM Avatar answered Sep 29 '22 11:09

IRTFM


1) mapply This does not give a list (2 below does) but it may be what you really want:

> mapply(do.call, fun_list, lapply(arg_list[names(fun_list)], list))
good better   best 
   3      2      6 

2) Map This gives a list as the result which is what was asked for. Its the same as (1) except mapply is replaced with Map:

> Map(do.call, fun_list, lapply(arg_list[names(fun_list)], list))
$good
[1] 3

$better
[1] 2

$best
[1] 6

Revised based on comments.

like image 22
G. Grothendieck Avatar answered Sep 29 '22 13:09

G. Grothendieck