title: R subscript out of bound error - for loop over custom function
body: <p>I've written a function to simulate genetic drift and i'm wanting to loop it over various values of t (number of generations), however whenever I do this I get the following error:</p>
  
  <pre><code>locifreq&lt;-runif(49, .4, 0.8)
  
  gen&lt;-1:100
  for (i in 1:length(gen)){
    pop[i]&lt;-lapply(locifreq,wright.fisher,3000,200,gen[i])
  }
  Error in `[&lt;-`(`*tmp*`, i, j, value = rbinom(1, 2 * N, prob = k[i - 1,  : 
    subscript out of bounds
  </code></pre>
  
  <p>I think it's because my function isn't able to generate the appropriate matrices or it's can't access the matrix within the list (though I may be completely wrong!), however I'm not sure how to fix this, as each attempt results in an incorrect number of subscripts.</p>
  
  <p>The code for my function is below</p>
  
  <pre><code>wright.fisher&lt;-function(p,Ne,nsim,t){
    N &lt;-Ne/2
    NA1 &lt;- 2*N*p 
    NA2 &lt;- 2*N*(1-p)
    k &lt;- matrix(0, nrow = t, ncol = nsim)
    k[1,] &lt;- rep(NA1, nsim) 
    for (j in 1:nsim) {
      for (i in 2:t) {
        k[i, j] &lt;- rbinom(1, 2*N, prob = k[i-1, j] / (2*N))  
      }
    }
    k &lt;- as.matrix(k/(2*N)) 
    t(k)
  }
  </code></pre>
  
  <p>Does anyone know how to fix this?</p>