[英]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.我有一个函数 MyFun(a,b,c,d),它返回数据框和图的列表。 The arguments, a, b, c, d, are just character strings that represent “start date”, “end date”, “current version #”, and “previous version #”.
参数 a、b、c、d 只是表示“开始日期”、“结束日期”、“当前版本#”和“上一个版本#”的字符串。 For brevity, I am going to call the arguments by the names a, b,c,d.
为简洁起见,我将通过名称 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.我想使用唯一的参数集运行 MyFun(a, b, c, d) 并将所有输出存储到列表中。 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)这是我不确定的部分:我正在尝试使用 Lapply 从 MyFun(a,b,c,d) 获取输出列表,使用 arg_sets 中列出的 3 个列表作为我的输入: 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].据我了解,上述 lapply 语句不起作用,因为 lapply 无法知道它应该传递给 MyFun 的一系列参数包含在 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).
作为替代方案,我还尝试将我的输入参数作为数据框传递给 lapply,其中包含 a、b、c、d 列,每行包含一组唯一的参数,我希望 lapply 传递给 MyFun(a, b ,光盘)。 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).
我无法定义 lapply 将输入矩阵的每一行作为一组参数传递给 MyFun(a,b,c,d)。
Any advice would be much appreciated!任何建议将不胜感激!
Use do.call
使用
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)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.