在r中循环嵌套for循环

时间:2014-09-04 13:27:31

标签: 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      
  }
}
}
}

0 个答案:

没有答案