简体   繁体   中英

Iterating a Function Using R Lapply and a List of Function Arguments

I have a function, MyFun(a,b,c,d), that returns a list of data frames and plots. The arguments, a, b, c, d, are just character strings that represent “start date”, “end date”, “current version #”, and “previous version #”. For brevity, I am going to call the arguments by the names a, b,c,d.

I want to run MyFun(a, b, c, d) with unique sets of arguments and store all the output into a list. To do so, I created a list of lists:

arg_set1 <- list(a1,b1,c1,d1)

arg_set2 <- list(a2,b2,c2,d2)

arg_set3 <- list(a3,b3,c3,d3)

arg_sets <- list(arg_set1, arg_set2, arg_set3)

This is the part I'm uncertain of: I am attempting to use Lapply to get a list of outputs from MyFun(a,b,c,d), using the 3 lists listed in arg_sets as my input: output <- lapply(arg_sets, MyFun)

To my understanding, the above lapply statement does not work because lapply is unable to know that the series of arguments it should pass to MyFun are contained in arg_sets[1], arg_sets[2], arg_sets[3]. As an alternative, I have also tried to pass my input arguments to lapply as a data frame, with columns of a,b,c,d and each row encompassing a unique set of parameters I want lapply to pass to MyFun(a, b,c,d). However, I ran into essentially the same issue as before with the list of input arguments; I am unable to define to lapply to pass each row of the input matrix as a set of arguments to MyFun(a,b,c,d).

Any advice would be much appreciated!

Use do.call

output <- lapply(arg_sets, function(x) do.call(my_fun, x))

See this simple example,

my_fun <- function(x, y , z) {
   x + y + z
}

arg_sets <- list(a = as.list(1:3), b= as.list(4:6))
lapply(arg_sets, function(x) do.call(my_fun, x))

#$a
#[1] 6

#$b
#[1] 15

If instead of list, you create a vector of arguments you can change the above function as

arg_set1 <- c(a1,b1,c1,d1)
arg_set2 <- c(a2,b2,c2,d2)
arg_set3 <- c(a3,b3,c3,d3)
arg_sets <- list(arg_set1, arg_set2, arg_set3)

lapply(arg_sets, function(x) do.call(my_fun, as.list(x)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM