2

当我使用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

  }

}

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

然后我也使用以下方法创建第三个函数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%" 

任何想法出了什么问题?

4

1 回答 1

0

foreach %dopar% 问题的快速解决方法是重新安装这些软件包:

install.packages("doSNOW")

install.packages("doParallel") 

install.packages("doMPI")

以上包负责 R 中的并行性。这些包的旧版本中存在的错误现在已删除。我应该提到,即使您没有在代码中使用这些包,它也很可能会有所帮助。

于 2017-08-21T09:15:11.530 回答