我试图使用foreach循环,但如果我尝试在循环中调整Gumbel分布,我会收到错误
"错误{:任务1失败 - "必须定义dgumbel函数""
我已经阅读了许多关于函数和foreach循环的帖子,他们似乎都建议将" .export = functionname"进入foreach线。我这样做了,不明白它为什么还没有运行。如果我排除Gumbel的拳击线并且只适合正态分布,那么一切正常。 如果我使用普通for循环,Gumbel分布的fitdist也可以正常工作。
# create data that will be used to fit a distribution
cum_prec <- matrix (nrow= 80, ncol=10)
x = c(1:6, 8:10)
for ( i in x){
cum_prec[,i] <- rnorm(80,400, 50)}
cum_prec[,7] <- rGumbel(80,400, 50)
# package fitdistrplus does not work for the gumbel distribution. Therefore, the gumbel distribution has to be added manually.
dgumbel <- function(x,a,b) {1/b*exp((a-x)/b)*exp(-exp((a-x)/b))}
pgumbel <- function(q,a,b) {exp(-exp((a-q)/b))}
qgumbel <- function(p,a,b) {a-b*log(-log(p))}
library(doParallel)
cl <- makeCluster(4)
registerDoParallel(cl)
clim <- foreach (n=1:10, .export=c("dgumbel", "pgumbel","qgumbel"), .combine= cbind, .packages= "fitdistrplus") %dopar%
{
rep=10000
normal <- matrix(nrow=rep, ncol=10)
x = c(1:6, 8:10)
for ( i in x){
Normal<-fitdist(cum_prec[,i],"norm")
normal[,i] <- rnorm(rep,Normal$estimate[1], Normal$estimate[2])
}
Gumbel<-fitdist(cum_prec[,7],"gumbel", start=list(a=0,b=1),optim.method="Nelder-Mead")
normal[,7] <- rGumbel(rep,Gumbel$estimate[1], Gumbel$estimate[2])
SU <- vector("numeric", rep)
for (i in 1:rep){
su = (quantile(normal[,1], probs=runif(1,0,1))+ quantile(normal[,2], probs=runif(1,0,1)) + quantile(normal[,3], probs=runif(1,0,1))
+ quantile(normal[,4], probs=runif(1,0,1))+ quantile(normal[,5], probs=runif(1,0,1))+ quantile(normal[,6], probs=runif(1,0,1))
+ quantile(normal[,7], probs=runif(1,0,1))+ quantile(normal[,8], probs=runif(1,0,1))+ quantile(normal[,9], probs=runif(1,0,1))
+ quantile(normal[,10], probs=runif(1,0,1)))/10
SU[i] <- su
}
}
stopCluster(cl)