user5935577
user5935577

Reputation:

Trying to use a for loop for population simulation

Im trying to use a for loop in r to run a population simulation for a period of 100 years however there is a problem with my code and each year has the same value. I know it relates to breedingPop but I cant figure out how to get the final breedingPop to be used for the each subsequent run of the loop. Here is my code:

SWWAyears<-read.csv("C:/Users/Bryan/Desktop/SWWAyears.csv")
SWWAyears$iteration<-NA
breedingPop<-84000
fallMig<-.815
winterSurvival<-.99
springMig<-.815
npFecund<-2.75
pFecund<-.60
breedingSurvival<-.99


for(years in 1:100){
    fallPop<-(breedingPop*fallMig)
    winterPop<-(fallPop*winterSurvival)
    springPop<-(winterPop*springMig)
    summerPop<-(springPop*breedingSurvival)
    breedingPop2<-(((summerPop*.26)*npFecund((summerPop*.14)*pFecund)+(summerPop*.60))  
    SWWAyears[,2]<-breedingPop2

    }

Upvotes: 1

Views: 94

Answers (1)

ZombiePlan37
ZombiePlan37

Reputation: 279

The solution I would take is to first set your starting breeding population size (84000) as a value in row 1 of your data frame. Then inside of your loop, you can reference the (year-1)th row to get this (previous year's) value, and record the new calculated value for the current year in the (year)th row. See below:

SWWAyears=data.frame(iteration=rep(NA,101),pop=NA)
breedingPop<-84000
fallMig<-.815
winterSurvival<-.99
springMig<-.815
npFecund<-2.75
pFecund<-.60
breedingSurvival<-.99

# Set initial starting condition
SWWAyears[1,2]=breedingPop

for(years in 2:101) {
  fallPop<-(SWWAyears[years-1,2]*fallMig)
  winterPop<-(fallPop*winterSurvival)
  springPop<-(winterPop*springMig)
  summerPop<-(springPop*breedingSurvival)
  breedingPop2<-((summerPop*.26)*npFecund+(summerPop*.14)*pFecund)+(summerPop*.60)
  SWWAyears[years,1]=years
  SWWAyears[years,2]<-breedingPop2             
}

Also, your initial breedingPop2 definition produced an error, so I adjusted it to what I believe you were intending - not sure if I got that part correct, but that should be a minor fix if needed.

Upvotes: 1

Related Questions