I'm trying to estimate the population growth of a population with different growths rates, shown below
r <-c(0.5, 1.0, 1.5, 2, 2.5, 2.6, 2.7, 2.8, 2.9)
I'm trying to fill N_List with the projection values associated with each r value.
I want the loop to run calculate 100 values with each r value and put it into N_list
However, I've run into an issue with filling the list. When I run the code it results in the list being filled with the same 100 values. I believe the problem is that the code loops through the r vector before the list is filled so it just inputs the same numbers into the list 9 times.
Here's the code I'm using, I've tried to move around code that is supposed to fill the list however I'm pretty new to R so I haven't had much luck.
#Parameters
N <- c()
N[1] <- 5 #Initial Population Size
N_list<-list() #Output List
t=seq(1,100,1)
r=c(0.5, 1.0, 1.5, 2, 2.5, 2.6, 2.7, 2.8, 2.9)
k=1000
#For Loop
for(replicate in 1:length(r)){
for(j in 1:length(r)) {
for (i in 1:(length(t)-1)) {
N[i+1] <- N[i] * exp(r[j] * (1 - (N[i]/k)))
}
}
N_list[[replicate]] <-N
}
Your code stores only the value of N when j = length(r) and it does that for every value of replicate. You should loop from 1 to length(r) only once and store N for every value of that loop.
N <- c()
N[1] <- 5 #Initial Population Size
N_list<-list() #Output List
t=seq(1,100,1)
r=c(0.5, 1.0, 1.5, 2, 2.5, 2.6, 2.7, 2.8, 2.9)
k=1000
for(j in 1:length(r)) {
for (i in 1:(length(t)-1)) {
N[i+1] <- N[i] * exp(r[j] * (1 - (N[i]/k)))
}
N_list[[j]] <-N
}