1
,我遇到這個奇怪的錯誤,系統將引發此[R的foreach找不到函數「%dopar%」
" 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
}
}
到目前爲止,一切都很好,我已經建立使用foreach
兩個功能ntw
和lambda
。他們完美地工作。
然後,我創建也使用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%"
任何想法是怎麼回事?
你不應該(不能?)並行化並行化的代碼。改爲使用嵌套運算符'%:%'。 (你應該認真考慮,如果你不能把你的一些循環變成矢量化的操作,那麼你的性能比並行化的相對小的增益提高几個數量級。) – Roland
謝謝@Roland,我重寫了程序,給了認爲前兩個函數使用'foreach'並且只有最後一個函數使用並行,這是有效的。至於矢量化,我不知道如何在我的情況下做到這一點。 – skyindeer