1
我已经检查了关于人口模拟的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=",")
太棒了!我必须记住你的方法。谢谢。 – ecologist55