I am trying to simulate populations in R, but my code currently includes nested for loops, which I would like to replace with apply loops so my code will run faster, though I'm not quite sure how. I've already read some existing topics about this, but I think my situation is different because I'm not just projecting growth, but reproduction and survivorship.
I have two vectors containing probabilities of survival and reproduction. I'll simulate some values for these.
St = rep(c(0.82, 0.89, 0.93), 3)
Bt = rep(c(0.13, 0.24, 0.17), 3)
What I want to do now is create a data frame with variables year, survivors, births, population size, and population growth. Year is trivial. The way I'm simulating the others is by killing off some of the starting population with whatever the survival probability is for that year, then applying the probability of reproduction to the survivors to get the number of births. Population size and growth are calculated from these. I have done this with two for loops nested inside a while loop.
count <- 0
years <- 9
population <- 200
survivors <- vector()
births <- vector()
growth <- vector()
while (count < years) {
count <- count + 1
for (i in St) {
survivors[count] <- rbinom(n=1, size=population[count], prob=i)
}
for (i in Bt) {
births[count] <- rbinom(n=1, size=survivors[count], prob=i)
}
growth[count] <- (population[count] - survivors[count]) + births[count]
population[count+1] <- population[count] + growth[count]
}
population <- population[2:length(population)]
year <- 1:years
data <- data.frame(year, births, survivors, population, growth)
Is there any way to generate this simulated time series using apply loops instead? I'm kind of stumped because the result of the births for loop in each year depends on the outcome of the survivors for loop.