title: R: Is it possible to use mutate+lag with the same column?
body: <p>I'm trying to replicate the following formula in R:</p>
  
  <p>Xt = Xt-1 * b + Zt * (1-b)</p>
  
  <p>I'm using the following code</p>
  
  <pre><code>t %&gt;% 
    mutate(x= ifelse(week == 1, z, NaN)) %&gt;% # Initial value for the first lag
    mutate(x= ifelse(week != 1, lag(x,1 ,default = 0) * b + z, z)
  </code></pre>
  
  <p>But I get all NaN except from the second element.</p>
  
  <pre><code>     z      b           x
       (dbl)  (dbl)    (dbl)
  1  168.895  0.9      168.8950
  2   20.304  0.9      131.7472
  3   14.943  0.9         NA
  4   11.028  0.9         NA
  5    8.295  0.9         NA
  6    8.024  0.9         NA
  7    6.872  0.9         NA
  8    7.035  0.9         NA
  9    4.399  0.9         NA
  10   4.158  0.9         NA
  </code></pre>
  
  <p>This is fairly simple in excel but I must do it in R, Do you have any approaches?</p>
  
  <p>Reproducible example:</p>
  
  <pre><code>set.seed(2)
  t = data.frame(week = seq(1:52),
                 z = runif(52, 0, 100),
                 b = 0.2)
  </code></pre>