Store last variable in a for loop equation into an array
<p>I'm trying to calculate the probability of extinction of a fictional lizard population size. To do this, I am running a for loop for 100 simulations over a period of 30 years, and seeing the probability of each simulation from going extinct. At the end of my 100 simulations, I need to plot a histogram depicting the final population size at the end of the 30 year interval. I figured that the easiest way to plot the histogram would be to create a different vector, and store the final population size of each simulation into this vector (<code>pop</code>). However, I have no idea how to code for this and have not found an answer online for my predicament.</p>

<p>I am using the following code:</p>

<pre><code>tmax &lt;- 31
runmax &lt;- 100
Year &lt;- 0:(tmax-1)
N &lt;- numeric(tmax) %vector for the population size
N &lt;- N + 1
epsilon &lt;- numeric(tmax) 
rmax &lt;- 0.87992 %maximum growth rate (a value previously calculated)
K &lt;- 34.64252 %carrying capacity (a value previously calculated)
N[1] &lt;- K
extinct &lt;- 0

for(t in 2:tmax){
    sdr &lt;- 0.9469428
    epsilon[t-1] &lt;- rnorm(1,0,sdr) %this takes into account the random population stochasticity (random chance a population will go extinct)
    N[t] &lt;- exp(rmax*(1-(N[t-1]/K))+epsilon[t-1])*N[t-1]
    if(N[t] &lt; 1.0) {
        N[t] &lt;- 0.0;break
    }
    pop=numeric(runmax)
    pop[1]=N[30]
}

extinct &lt;- extinct + ifelse(N[tmax]&lt;=1,1,0)

plot(Year,N,type='l',ylim=c(0,200))

for(i in 1:runmax){
    N &lt;- numeric(tmax)
    N &lt;- N+1
    N[1] &lt;- K
    for(t in 2:tmax){
        sdr &lt;- 0.9469428
        epsilon[t-1] &lt;- rnorm(1,0,sdr) 
        N[t] &lt;- exp(rmax*(1-(N[t-1]/K))+epsilon[t-1])*N[t-1]
        if(N[t] &lt; 1.0) {
            N[t] &lt;- 0.0
            break
        }
    for(w in 2:runmax){
        pop[w]&lt;- N[30]
    }
}

extinct &lt;- extinct + ifelse(N[tmax]&lt;=1,1,0)
lines(Year,N,col=i)
}
</code></pre>

<p>So in the above code, <code>pop</code> is the vector where I'm storing the population at <code>N[30]</code>. The idea is then to use <code>hist(pop)</code> to plot the histogram.</p>

<p>Thanks in advance!</p>