Global Assignment, Parallelism, and foreach

╄→гoц情女王★ 提交于 2019-12-01 11:46:54

Your attempts to assign to global variables in the foreach loop are failing because they are happening on the worker processes that were forked by mclapply. Those variables aren't sent back to the master process, so they are lost.

You could try something like this:

r <- foreach(i = 1:3) %dopar% {
  if (i == 1) {
    bigAnalysis(data1)
  } else if (i == 2) {
    bigAnalysis(data2)
  } else {
    bigAnalysis(data3)
  }
}

a <- r[[1]]
b <- r[[2]]
c <- r[[3]]
ls(a)

This uses the default combine function which returns the three environment objects in a list.

Executing the foreach loop in a function isn't going to make it work. However, the assignments would work if you didn't call registerDoMC so that you were actually running sequentially. In that case you really are making assignments to the master process's global environment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!