加速r中循环中的嵌套循环
一个循环中有两个for循环。我想出这个来填充矩阵列表。我的矩阵列表定义如下(我有七个列表,每个列表包含1000个矩阵)。我有七个变量(ncol=7),我有七个不同的计算(h2,cvm,cve,mean,wfv,bfv)。这些计算我必须对每次随机采样的数据帧执行1000次,因此是1000个矩阵。这个循环很有效,我已经尝试了100个矩阵的列表,但是,10000个矩阵需要超过1 1/2天(我取消了它,因为我不能再等了。你对我如何加速这个循环有什么好的建议吗?代码旁边是对每个循环中发生的事情的逐步描述。非常感谢加速r中循环中的嵌套循环,r,for-loop,sample,R,For Loop,Sample,一个循环中有两个for循环。我想出这个来填充矩阵列表。我的矩阵列表定义如下(我有七个列表,每个列表包含1000个矩阵)。我有七个变量(ncol=7),我有七个不同的计算(h2,cvm,cve,mean,wfv,bfv)。这些计算我必须对每次随机采样的数据帧执行1000次,因此是1000个矩阵。这个循环很有效,我已经尝试了100个矩阵的列表,但是,10000个矩阵需要超过1 1/2天(我取消了它,因为我不能再等了。你对我如何加速这个循环有什么好的建议吗?代码旁边是对每个循环中发生的事情的逐步描述。
list.h2 <- rep(list(matrix(nrow = length(levels(h2$spec.plot)), ncol = 7)),1000)
list.cvm <- rep(list(matrix(nrow = length(levels(h2$spec.plot)), ncol = 7)),1000)
list.cve <- rep(list(matrix(nrow = length(levels(h2$spec.plot)), ncol = 7)),1000)
list.mean <- rep(list(matrix(nrow = length(levels(h2$spec.plot)), ncol = 7)),1000)
list.wfv<-rep(list(matrix(nrow = length(levels(h2$spec.plot)), ncol = 7)),1000)
list.bfv<-rep(list(matrix(nrow = length(levels(h2$spec.plot)), ncol = 7)),1000)
## bind everything into a list of lists
res.list <- list(list.h2, list.cvm, list.mean, list.cve, list.wfv, list.bfv)
names(res.list) <- c("h2", "cvm", "mean", "cve", "wfv", "bfv")
require(plyr)
library(lme4)
for(f in 1:1000){ # 1000 runs
dd<- ddply(h, .(spec_name),summarize, ans=sample(spec_sf)) #sample the dataframe 1000 times
names(dd)<-c("species","m_spec_sf")
h_dd1<-cbind(h,dd["m_spec_sf"]) #bind the new sampled dataframe to the original dataframe 'h'
h_dd<-h_dd1[c(1:12,21,14:20)]
for(j in 1:7){ # 7 is the number of response variables which i want to do the below calculations on
for(i in 1:length(levels(spec.plot))){ # the levels I want to do the below calculations within
sub.mat <- h_dd[spec.plot==levels(spec.plot)[i], ] # create matrix with values for only one spec x plot combination
means <- tapply(sub.mat[, j+13], as.character(sub.mat$m_spec_sf), mean, na.rm=T)
### means
res.list[["mean"]][[f]][i,j] <- mean(sub.mat[,j+13], na.rm=T)
### model: use try to stop the whole loop breaking if the model doesn't fit
m<-try(lmer(h_dd[, j+13]~1+(1|m_spec_sf), subset=spec.plot==levels(spec.plot)[i],data=h_dd))
if(class(m)=="try-error"){ ## remove failed models
res.list[["h2"]][[f]][i,j] <- NA}
else{
VCg<-as.numeric(VarCorr(m)) #insert all results from below calculations into the list of matrices
VCe<-attr(VarCorr(m),"sc")^2
res.list[["h2"]][[f]][i,j] <- 4(VCg/(VCg+VCe))
res.list[["cve"]][[f]][i,j] <- sqrt(VCe)/mean(means, na.rm=T)
res.list[["cvm"]][[f]][i,j] <- sqrt(VCg)/mean(means, na.rm=T)
res.list[["bfv"]][[f]][i,j] <- VCg
res.list[["wfv"]][[f]][i,j] <- VCe
}
}
}
}
list.h2首要任务是分析您的代码。然而,显然您正在尝试适应成千上万的lmer
模型。如果速度慢,您不应该感到惊讶。@Roland抱歉,分析代码是什么意思?是lmer使其变慢了吗?也许有办法改进循环,使其更快?Stufy帮助(“Rprof”)
慢的不是循环,而是你在循环中所做的事情。我只是指出,lmer
相对来说比较慢,而且不适合经常调用。可能还有其他一些慢的操作,可以改进,但是通过分析比我们试图理解你的不可复制性更容易找到它们代码。@Roland就可以了!谢谢你的评论!