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