在 R 中并行运行 for 循环

标签 r parallel-processing parallel-foreach

我有一个类似这样的 for 循环:

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

}

你能告诉我如何做这个平行吗?

我根据在线示例尝试了此操作,但不确定语法是否正确。它也没有提高太多速度。

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

   cbind(finalMatrix, tempMatrix)

}

最佳答案

感谢您的反馈。在发布这个问题后,我确实查了一下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)

注意 - 我必须添加一条注释,如果用户分配太多进程,则用户可能会收到此错误:序列化错误(数据,node$con):写入连接时出错

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

希望这对像我一样第一次尝试 R 并行处理的人有用。

引用文献: http://www.r-bloggers.com/parallel-r-loops-for-windows-and-linux/ https://beckmw.wordpress.com/2014/01/21/a-brief-foray-into-parallel-processing-with-r/

关于在 R 中并行运行 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38318139/

相关文章:

r - 使用 quantstrat 执行多时间框架策略的正确方法是什么?

r - 使用 Fivethirtyeight ggtheme 将 ylab 添加到 ggplot

PostgreSQL如何在多个CPU之间拆分查询

r - 如何加快随机森林的训练速度?

r - 使用 SparkR 获取特定行

r - 在xtable中设置不同的数字

c - MPI 函数 MPI_Comm_split_type 中的 "int key"参数是什么?

c - 传递私有(private)变量时出现 Openmp 段错误,但在并行区域内声明变量时不会出现

r - 了解并行TSQL连接

r - 在 R foreach() 下并行运行时无法识别动态库依赖项