title: dplyr: Iterative calculation
body: <p>I'm trying to figure out if there's a way for dplyr to calculate a variable row-by-row, such that it can reference the results calculated one record prior. </p>
  
  <p>Here is code that achieves what I want using for-loops:</p>
  
  <pre><code>x &lt;- data.frame(x1 = c(1:10)) 
  
  #This works.
  x$x2[1] &lt;- 0
  
  for (i in 2:nrow(x)) {
    x$x2[i] &lt;- x$x2[i-1]*1.1 + 1
  }
  </code></pre>
  
  <p>My naive deplyr attempt, which doesn't work:</p>
  
  <pre><code>#This doesn't work. "Error: object'x1' not found"
  x %&gt;% mutate(x2 = ifelse(x1 == 1, 0, lag(x2)*1.1 + 1))
  </code></pre>
  
  <p>It would be nice to find a dplyr solution since this step is part of a workflow that heavily relies on it. </p>
  
  <p>Thank you.</p>
  
  <hr>
  
  <p><strong>Edit:</strong></p>
  
  <p>The above is a simplified example of what I'm trying to do. A closed form solution will not work because the function applied is more complex and dynamic than what is shown here. For example, suppose that 'add_var' and 'pwr_var' are random integers, and I want to calculate this:</p>
  
  <pre><code>x$x2[1] &lt;- 0
  
  for (i in 2:nrow(x)) {
    x$x2[i] &lt;- ( x$x2[i-1]*1.1 + x$add_var[i] ) ^ x$pwr_var[i]
  }
  </code></pre>