title: Simulating a timeseries in dplyr instead of using a for loop
body: <p>So, while <code>lag</code> and <code>lead</code> in dplyr are great, I want to simulate a timeseries of something like population growth.  My old school code would look something like:</p>
  
  <pre><code>tdf &lt;- data.frame(time=1:5, pop=50)
  for(i in 2:5){
    tdf$pop[i] = 1.1*tdf$pop[i-1]
  }
  </code></pre>
  
  <p>which produces</p>
  
  <pre><code>  time    pop
  1    1 50.000
  2    2 55.000
  3    3 60.500
  4    4 66.550
  5    5 73.205
  </code></pre>
  
  <p>I feel like there has to be a <code>dplyr</code> or <code>tidyverse</code> way to do this (as much as I love my for loop).</p>
  
  <p>But, something like</p>
  
  <pre><code>tdf &lt;- data.frame(time=1:5, pop=50) %&gt;%
    mutate(pop = 1.1*lag(pop))
  </code></pre>
  
  <p>which would have been my first guess just produces</p>
  
  <pre><code>  time pop
  1    1  NA
  2    2  55
  3    3  55
  4    4  55
  5    5  55
  </code></pre>
  
  <p>I feel like I'm missing something obvious.... what is it?</p>
  
  <p>Note - this is a trivial example - my real examples use multiple parameters, many of which are time-varying (I'm simulating forecasts under different GCM scenarios), so, the tidyverse is proving to be a powerful tool in bringing my simulations together.</p>