R foreach找不到功能“%dopar%”

时间:2016-04-12 11:36:11

标签: r foreach parallel-processing doparallel

当我使用doParallel库时,我遇到了这个奇怪的错误,系统抛出了这个

" Error in { : task 1 failed -could not find function "%dopar%"

具体来说,这就是我所做的

library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)
# Read the data
coin95 <-read.csv('~/Documents/coin95.csv')
coin95 <- coin95[,!(names(coin95) %in% c("X"))]
coin95[c("Person")] <- sapply(coin95[c("Person")],as.character)
# create the name list
coin95_name <- as.character(coin95$Person)  
coin95_name <- unique(coin95_name)
n <- as.numeric(length(coin95_name))

# the average counting process

ntw <- function(now){
  foreach (Ii = coin95_name,.combine = "+",.export = c("coin95","n")) %dopar% {
    time <-subset(coin95, subset = coin95$Person == Ii)$duration
    stepfun(time,seq(0,length(time)))(now)/n
  }
}

# the average cumulative hazard
lambda <- function(now,params){
  b <- params[1]
  sigma <- params[2]
  mu <- params[3]
  xi <- params[4]
  beta1 <- params[5]
  beta2 <- params[6]

  k <- function(spread){
    L0 <- (1+(spread -mu)*xi/sigma)^(-1/xi)
    return(L0)
  }

  foreach(Ii = coin95_name,.combine = "+",.export = c("coin95","n")) %dopar% {
    time <- subset(coin95, subset = coin95$Person == Ii)$duration
    noncov <- subset(coin95, subset = coin95$Person == Ii)$noncovered
    reim <- subset(coin95, subset = coin95$Person == Ii)$reimbursement
    (b*now+sum( exp(-k(now-time[(time < now)])+beta1*noncov[(time < now)]+beta2*reim[(time <now)]) ))/n

  }

}

到目前为止,一切都很好,我使用ntw创建了两个函数lambdaforeach。他们工作得很好。

然后我也使用foreach创建第三个函数:

# the distance
Time <- coin95$duration
Time <- sort(as.double(Time))

jl <- function(params){
       res<-foreach(Ii = Time,.combine = "rbind",.export = c("ntw","lambda")) %dopar% {
         (ntw(Ii)-ntw(Ii-1e-7)) * (ntw(Ii)- lambda(Ii,params))^2
         }
       return(sqrt(sum(res))) 
     }

guess<-c(0.0,1.3333,0.0,0.1,-1.2,3e-3)

输入jl(guess)

> jl(guess)
 Show Traceback

 Rerun with Debug
 Error in { : task 1 failed -could not find function "%dopar%" 

任何想法出了什么问题?

1 个答案:

答案 0 :(得分:0)

快速修复foreach%dopar%的问题是重新安装这些软件包:

install.packages("doSNOW")

install.packages("doParallel") 

install.packages("doMPI")

上面的软件包负责R中的并行性。现在删除了旧版本软件包中存在的Bug。我应该提一下,即使您没有在代码中使用这些软件包,它也很有可能会有所帮助。