无法在R中并行化具有多个参数的函数

问题描述

我试图并行化一个简单的函数,该函数将两个数字相加并使用库R中的mclapplyparallel中打印结果。这是我的代码

library(doParallel)
t = list(list(1,1),list(2,2),list(3,3))
f <- function (a,b){
    print(a + b)
}
mclapply(t,f)

但是它返回错误

Warning message in mclapply(t,f):
“all scheduled cores encountered errors in user code”
[[1]]
[1] "Error in print(a + b) : argument \"b\" is missing,with no default\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in print(a + b): argument "b" is missing,with no default>

[[2]]
[1] "Error in print(a + b) : argument \"b\" is missing,with no default>

[[3]]
[1] "Error in print(a + b) : argument \"b\" is missing,with no default>

有人可以告诉我我在做什么错吗?

我试图搜索如何并行运行带有多个参数的函数,但是没有找到答案。

解决方法

mclapply正在为本身就是列表的列表的每个元素调用函数。因此,每次调用该函数时,都将其传递给列表,而不是其他任何东西。您需要在函数中解压缩列表:

library(doParallel)
t = list(list(1,1),list(2,2),list(3,3))
f <- function (a){
  print(a[[1]] + a[[2]])
}
mclapply(t,f)