在R中并行运行for循环

kay*_*kay 39 parallel-processing r parallel-foreach

我有一个for循环,它是这样的:

for (i=1:150000) {
   tempMatrix = {}
   tempMatrix = functionThatDoesSomething() #calling a function
   finalMatrix =  cbind(finalMatrix, tempMatrix)

}
Run Code Online (Sandbox Code Playgroud)

你能告诉我如何让它平行吗?

我在网上尝试了这个例子,但我不确定语法是否正确.它也没有太多提高速度.

finalMatrix = foreach(i=1:150000, .combine=cbind) %dopar%  {
   tempMatrix = {}
   tempMatrix = functionThatDoesSomething() #calling a function

   cbind(finalMatrix, tempMatrix)

}
Run Code Online (Sandbox Code Playgroud)

kay*_*kay 66

感谢您的反馈意见.parallel在我发布这个问题后我确实抬起头来.

经过几次尝试后,我开始运行了.我已经添加了下面的代码,以防它对其他人有用

library(foreach)
library(doParallel)

#setup parallel backend to use many processors
cores=detectCores()
cl <- makeCluster(cores[1]-1) #not to overload your computer
registerDoParallel(cl)

finalMatrix <- foreach(i=1:150000, .combine=cbind) %dopar% {
   tempMatrix = functionThatDoesSomething() #calling a function
   #do other things if you want

   tempMatrix #Equivalent to finalMatrix = cbind(finalMatrix, tempMatrix)
}
#stop cluster
stopCluster(cl)
Run Code Online (Sandbox Code Playgroud)

注意 - 我必须添加一个注释,如果用户分配了太多进程,那么用户可能会收到此错误: Error in serialize(data, node$con) : error writing to connection

注 - 如果.combineforeach语句中rbind,则返回的最终对象将通过逐行追加每个循环的输出来创建.

希望这对于像我这样第一次在R中尝试并行处理的人来说非常有用.

参考文献:http : //www.r-bloggers.com/parallel-r-loops-for-windows-and-linux/ https://beckmw.wordpress.com/2014/01/21/a-brief-foray-成并行处理与- R /

  • 请注意,如果 %dopar% 循环中的代码包含来自外部包的任何函数,则必须将 library() 调用放在 * 内部 * 循环中。 (3认同)
  • @ user1700890,这可能会回复您的问题/sf/ask/1385412661/ (2认同)
  • @mikoontz也可以通过foreach的.packages参数来实现,例如,foreach(i = 1:150000,.combine = cbind,.packages = c(“ dplyr”,“ tidyr”)).. 。 (2认同)