Cha*_*lie 25 parallel-processing r
我试图在几个核心上运行代码(我尝试了两个snow和parallel包).我有
cl <- makeCluster(2)
y <- 1:10
sapply(1:5, function(x) x + y) # Works
parSapply(cl, 1:5, function(x) x + y)
Run Code Online (Sandbox Code Playgroud)
最后一行返回错误:
Error in checkForRemoteErrors(val) :
2 nodes produced errors; first error: object 'y' not found
Run Code Online (Sandbox Code Playgroud)
显然parSapply没有y在全球环境中找到.有办法解决这个问题吗?谢谢.
Jos*_*ich 23
节点不知道y主节点上的全局环境.你需要以某种方式告诉他们.
library(parallel)
cl <- makeCluster(2)
y <- 1:10
# add y to function definition and parSapply call
parSapply(cl, 1:5, function(x,y) x + y, y)
# export y to the global environment of each node
# then call your original code
clusterExport(cl, "y")
parSapply(cl, 1:5, function(x) x + y)
Run Code Online (Sandbox Code Playgroud)
值得一提的是,如果parSapply从函数内部调用,您的示例将起作用,尽管真正的问题function(x) x + y是创建函数的位置.例如,以下代码正常工作:
library(parallel)
fun <- function(cl, y) {
parSapply(cl, 1:5, function(x) x + y)
}
cl <- makeCluster(2)
fun(cl, 1:10)
stopCluster(cl)
Run Code Online (Sandbox Code Playgroud)
这是因为在其他函数中创建的函数与创建它们的本地环境一起序列化,而从全局环境创建的函数不与全局环境一起序列化.这有时很有用,但如果你不知道这个问题,它也会导致各种各样的问题.