在R中并行运行for循环

在R中并行运行for循环,r,parallel-processing,parallel-foreach,R,Parallel Processing,Parallel Foreach,我有一个类似这样的for循环: for (i=1:150000) { tempMatrix = {} tempMatrix = functionThatDoesSomething() #calling a function finalMatrix = cbind(finalMatrix, tempMatrix) } 你能告诉我怎么做这个比较吗 我根据一个在线示例尝试了这个方法,但不确定语法是否正确。它也没有增加多少速度 finalMatrix = foreach(i=1:

我有一个类似这样的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)
库(foreach)
图书馆(双平行)
#设置并行后端以使用多个处理器
核心=检测核心()

cl并行运行需要相当多的开销。只有当
功能完成方法时,你才能获得相当大的速度。我认为在这篇文章合格之前,你还需要做很多工作。例如,查找
parallel
doParallel
包……您不应该需要这个--
cbind(finalMatrix,tempMatrix)
——如果您使用
.combine
参数,只需返回函数输出。我可以从并行循环返回多个不同的对象吗。例如,我想返回dataframe和vector/list?@user1700890,这可能会回答您的问题:如果%dopar%循环中的代码包含来自外部包的任何函数,则必须将库()放入在循环内部调用。@Mikontz这也可以通过
foreach
packages
参数来完成,例如
foreach(i=1:150000,.combine=cbind,.packages=c(“dplyr”,“tidyr”)…
为了优化的目的,一定要尝试比较
detectores()
detectores(logical=FALSE)
。如果在大多数情况下,您的所有处理器的使用率达到97%或以上,那么您的程序最喜欢使用
detectCores(logical=FALSE)
运行得更快,否则使用
detectCores()