R: apply function list to argument list by name

Someone decided my question to apply the list of functions in the list of arguments by order , now I have another similar question, how to apply the 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 a list of functions called by their named parameter, i.e. I want:

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

What would be a good way to do this?

+8
r
source share
3 answers

1) mapply This does not give a list (2 below), 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 the list as the result that was requested. Its the same as (1), except for mapply , it is replaced by 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.

+5
source share

As I understand it, you want to select functions and arguments from lists, not necessarily in order, but having 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 was not all clear if you wanted results, but that was what I had expected. If you really need invaluable expressions, you will need to clarify.

+10
source share

A magic function is possible here:

 > some_magic_fun <- function(funList, argList){ m <- match(nmf <- names(funList), names(argList)) l <- lapply(seq(m), function(i) funList[[i]](m[i])) setNames(l, nmf) } > some_magic_fun(fun_list, arg_list) # $good # [1] 3 # # $better # [1] 2 # # $best # [1] 6 

Keep in mind that this will only work on named lists and will need to be adjusted for unnamed lists. And also that the last line is optional, and I added it, although your desired result is an unnamed list.

+5
source share

All Articles