R 并行:错误 "could not find function "%do%""

R parallel: error "could not find function "%do%""

这是一段 R 代码(函数 "Kclust"),它尝试使用库 (doParallel) 并行执行任务。

  result = foreach (r = rseq, .combine=c) %dopar% {
    K=apply(D, 1, function(v){sum(v <= r)-1})
    L=sqrt((diff(xlim)+2*max(rseq))*(diff(ylim)+2*max(rseq))* K /(pi * (dim(tor)[1]-1)))
    foreach (th = thseq) %do% {
      C=which(L>=th)
      if (length(C)>0){
        G = graph.adjacency(D[C,C] < 2 *r)
        lab=clusters(G, "weak")
        labels=(N+1):(2*N); labels[C]=lab$membership
      }
      else labels=1:N
      s=0
      if (score){
        s=scorewprec(labels=labels, pts=pts, sds=sds, xlim=xlim, ylim=ylim, psd=psd, minsd=minsd, maxsd=maxsd, useplabel=useplabel, alpha=alpha, pb=pb)
      }
      list("scale" = r, "score" = s, "thresh" = th, "labels" = labels)
    }
  }

代码 运行 适合:

R 版本 3.0.2 (2013-09-25) -- "Frisbee Sailing"。 平台:x86_64-pc-linux-gnu(64 位)

但是,如果我 运行 代码为:

R 版本 3.2.3 (2015-12-10) -- "Wooden Christmas-Tree"。 平台:x86_64-w64-mingw32/x64(64 位)。

我明白了

Error in { : task 1 failed - "could not find function "%do%"" Calls: sapply -> lapply -> FUN -> Kclust -> %dopar% -> Execution halted

可能是什么问题?

正如@Roland 在他的评论中提到的那样,您必须将 foreach 包导出给各个工人。可以这样做:

result = foreach (r = rseq, .combine=c, .packages = c("foreach")) %dopar% {
  #some code...
  # now use the foreach function from the foreach package again
  foreach (th = thseq) %do% {
  #...
  }
}

就像这样,你必须将所有使用过的库作为字符向量导出给工人。因此我添加了 c("packageA", "packageB", "etc.")