【发布时间】:2015-02-27 20:27:14
【问题描述】:
我使用foreach 包中的%dopar% 在本地并行运行任务,使用doSNOW 包创建集群(目前在Windows 机器上运行)。我以前做过很多次,它工作正常,直到我在其中使用%do%(即非并行)放置一个不相关的foreach循环。然后 R 给了我错误(带有回溯):
Error in { : task 1 failed - "could not find function "%do%"" 3 stop(simpleError(msg, call = expr)) 2 e$fun(obj, substitute(ex), parent.frame(), e$data) 1 foreach(rc = 1:5) %dopar% {
aRandomCounter = -1
if (1 > 0) {
for (batchi in 1:20) { ...
下面是一些在我的机器上复制问题的代码:
require(foreach)
require(doSNOW)
cl<-makeCluster(5)
registerDoSNOW(cl)
for(stepi in 1:10) # normal outer for
{
foreach(rc=1:5) %dopar% # the time consuming stuff in parallel (not looking to actually retrieve any data)
{
aRandomCounter = -1
if(1 > 0)
{
for(batchi in 1:20)
{
anObjectIwantToCreate <- foreach( qrc = 1:100, .combine=c ) %do%
{
return(runif(1)) # I know this is not efficient, it is a placeholder to reproduce the issue
}
aRandomCounter = aRandomCounter + sum(anObjectIwantToCreate > 0.5)
}
}
return(aRandomCounter)
}
}
stopCluster(cl)
用简单的for 或(l/s)apply 替换内部foreach 是一种解决方案。但是有没有办法使这个工作与内部foreach 一起工作,为什么首先会出现错误?
【问题讨论】:
-
在 SO 上发布的代码中嵌入
rm(list=ls())语句被认为是非常不礼貌的。试图帮助您的人可能会意外清除他们的整个会话,这可能需要数小时才能重建。这就是我评论它的原因。不要再这样做了。