保存循环的每个循环的结果

时间:2016-03-25 18:01:14

标签: r loops

我已经在Stackoverflow上检查了几个关于人口模拟的问题,但我似乎无法找到解决方案。

我的问题是如何在保存每个循环的输出的同时将第1年的结束人口数据携带到第2年(循环2)等等。

我已经包含了代码和评论,以帮助读者了解我在做什么。我意识到一些代码看起来是不必要的,但我把它们放在这个简化的例子中(完整的代码有更多的年龄类,矩阵和死亡事件)。

sum_mat<-matrix(rep(0,3*3),nrow=3) # template for summer matrix

onf=0                         # Initial number of calves (hypothetical population)
ony=250                     # Initial number of yearlings
ona2=500          # Initial number of cows

cc<- c(0.46,0.33,0.16,0.36,0.42) #observed calf:cow ratios

#nyears=10

#for (i in 1:nyears)
#{
# SUMMER
pop0= c(onf,onf,onf,
    ony,ony,ony,
    ona2,ona2,ona2) # vector of age structure at the beginning of summer

cc2=sample(cc,1)    # sample from observed calfcow ratios for each loop/year

cowsurv=rnorm(n=1,mean=0.1,sd=.05) #randomly select mortality rate for females

sy_s= (1-(cowsurv)) # yearlings summer survival
sa2_s=(1-(cowsurv)) # adult summer survival

#leslie matrix for summer
sum_mat[1,]=c(0,sy_s*cc2,sa2_s*cc2) #fecundity
sum_mat[2,]=c(0,sy_s,0) 
sum_mat[3,]=c(0,0,sa2_s)

demo_s=pop0*sum_mat                     # Matrix transition process

pop1=c(sum(demo_s[1,]),sum(demo_s[1,]),sum(demo_s[1,]),
   sum(demo_s[2,]),sum(demo_s[2,]),sum(demo_s[2,]),
   sum(demo_s[3,]),sum(demo_s[3,]),sum(demo_s[3,]))

pop0<-c(pop0[1],pop0[4],pop0[7]) #extract N calves, yearlings, adults pre-  summer
pops<-c(pop1[1],pop1[4],pop1[7]) #extract N calves, yearlings, adults post-summer
ccmod<-rep(cc2,3) #extract calfcow ratio
age<-c('calf','1','2') #add age-class identifier
stats<-cbind(age,pop0,pops,ccmod) #combine the extracted values
stats<-as.data.frame(stats) 
#stats$year<-[i] #add simulation year
write.csv(stats,"popmodel.csv",row.names=FALSE)

#}

#######################################
######### year 2 ######################
#######################################

onf=0                     # no calves in new pre-summer year 
ony=pops[1]             #calves during post-summer are now yearlings
ona2=pops[2]+pops[3]       #yearlings during post-summer now adults,added to   existing summer adults

# repeat above procedure for with new population, append each year to existing csv

write.table(stats, file="popmodel.csv", append=T,    row.names=F,col.names=F,sep=",")

1 个答案:

答案 0 :(得分:0)

考虑一个条件for循环,其中第一年采用与所有其他年份不同的路线,特别是输入变量和输出文件。

# INITIALIZE VARIABLES
sum_mat <- matrix(rep(0,3*3),nrow=3)  # Template for summer matrix
cc <- c(0.46,0.33,0.16,0.36,0.42)     # Observed calf:cow ratios

nyears <- 10

# LOOP THROUGH YEARS
for (i in 1:nyears)
{
   # CONDITION INPUT VARIABLES BY FIRST VS ALL OTHER YEARS
   if (i == 1) {
       onf  <- 0                     # Initial number of calves (hypothetical population)
       ony  <- 250                   # Initial number of yearlings
       ona2 <- 500                   # Initial number of cows

   } else {
       onf  <- 0                     # No calves in new pre-summer year 
       ony  <- pops[1]               # Calves during post-summer are now yearlings
       ona2 <- pops[2]+pops[3]       # Yearlings during post-summer now adults,added to existing summer adults
   }

   # SUMMER
   pop0 <- c(onf,onf,onf,
           ony,ony,ony,
           ona2,ona2,ona2)             # Vector of age structure at the beginning of summer

   cc2  <- sample(cc,1)                # Sample from observed calfcow ratios for each loop/year

   cowsurv=rnorm(n=1,mean=0.1,sd=.05)  # Randomly select mortality rate for females

   sy_s  <- (1-(cowsurv))              # Yearlings summer survival
   sa2_s <- (1-(cowsurv))              # Adult summer survival

   # Leslie matrix for summer
   sum_mat[1,] <- c(0,sy_s*cc2,sa2_s*cc2)  # Fecundity
   sum_mat[2,] <- c(0,sy_s,0) 
   sum_mat[3,] <- c(0,0,sa2_s)

   demo_s <- pop0*sum_mat                  # Matrix transition process

   pop1 <- c(sum(demo_s[1,]),sum(demo_s[1,]),sum(demo_s[1,]),
             sum(demo_s[2,]),sum(demo_s[2,]),sum(demo_s[2,]),
             sum(demo_s[3,]),sum(demo_s[3,]),sum(demo_s[3,]))

   pop0  <- c(pop0[1],pop0[4],pop0[7])     # Extract N calves, yearlings, adults pre-summer
   pops  <- c(pop1[1],pop1[4],pop1[7])     # Extract N calves, yearlings, adults post-summer
   ccmod <- rep(cc2,3)                     # Extract calfcow ratio
   age   <- c('calf','1','2')              # Add age-class identifier
   stats <- cbind(age,pop0,pops,ccmod)     # Combine the extracted values
   stats <- as.data.frame(stats)     

   stats$year <- i                         # Add simulation year

   # CONDITION OUTPUT BY FIRST VS ALL OTHER YEARS
   if (i == 1) {
        write.csv(stats,"popmodel.csv",row.names=FALSE)
   } else {
        write.table(stats, file="popmodel.csv", append=T, row.names=F,col.names=F,sep=",")
   }

}