for循环存储问题(嵌套for循环)

时间:2013-10-25 17:24:03

标签: r for-loop nested-loops

我很难将所有数据存储在我的中间循环中。当我尝试在外部for循环运行后检索数据时,我能够获得的唯一数据是最终运行。如何在单个矩阵中存储D的所有运行?

set.seed(3690)

iterations <- 20
mean_birthrate <- 0.4
stand_dev_birthrate <- 0.1
mean_survival_rate <- 0.68
stand_dev_survival <- 0.07
initial_population <- 100
period <- 20
End_Year <- 2013+period

birthrate <- rnorm(n=1,mean=mean_birthrate,sd=stand_dev_birthrate)
birthrate
survival <- rnorm(n=1,mean=mean_survival_rate,sd=stand_dev_survival)
survival

 growth_rate <- birthrate - (1-survival)
 growth_rate


 for (k in 1:50) {
 D <- numeric(period)
 D[1] <- initial_population

 for (i in 1:period) {
  D[i+1] <- D[i] + ((rnorm(n=1,mean=mean_birthrate,sd=stand_dev_birthrate) -  (1-rnorm(n=1,mean=mean_survival_rate,sd=stand_dev_survival))) * D[i]) 
  }

 print(D)

 if (k==1)
 plot(D, typ="l",ylab="Number of Bobcats",xlab="Year",ylim=c(50,1700),xaxt='n')
 if (k>1)
 lines(D,col = rgb(0,0,0,0.1),xaxt='n')
}

2 个答案:

答案 0 :(得分:0)

如果您有嵌套的for循环,则需要嵌套的lists(或其他一些形式来捕获n x m多个结果)

 #outter loop
 for (i in...)
   D[[i]]  <- list()

   #inner loop
   for (j in ...)
     D[[i]][[j]]  <- value
     # or different syntax:
     D[[c(i, j)]] <- calue

答案 1 :(得分:0)

我遇到了类似的问题,并使用预定义的变量解决了这个问题,如下所示:

DATA <- list()
j <- 0
for(k in 1:10){
  for(i in 1:5){
    temp.DATA <- i*k #or whatever the loop does
    j <- j+1
    DATA[[j]] <- temp.DATA
  }
}
DATA2 <- do.call(rbind.data.frame, DATA)

希望有所帮助!