R: apply function list to argument list

Say I have several functions in a list and several arguments in another list (they are arranged so that each function calls the correct argument):

fun_list <- list(f1, f2, f3) arg_list <- list(a1, a2, a3) 

Is there a function in R that would apply fun_list to arg_list accordingly? In particular, I want:

 fun_apply(fun_list, arg_list) == list(f1(a1), f2(a2), f3(a3)) 
+2
r
source share
2 answers

Use Map . ( Map is basically mapply with a default value of SIMPLIFY = FALSE .) For example:

 fns <- list(mean, median, sum) values <- list(1:5, 3:7, 5:9) Map( function(fn, value) { fn(value) }, fns, values ) 
+6
source share

Something like this if you just want the names of the arguments and functions in the list:

 f1 <- f2 <- f3 <- function(x) x a1 <- a2 <- a3 <- "14"; fun_list <- list("f1", "f2", "f3") arg_list <- list("a1", "a2", "a3") mapply(function(x, y) eval(parse(text=paste(x, "(", y, ")", sep=""))), fun_list, arg_list) 

If you do not need the names in the list, but the actual arguments and functions:

 fun_list <- list(f1, f2, f3) arg_list <- list(a1, a2, a3) mapply(function(x, y) x(y), fun_list, arg_list) 
+1
source share

All Articles