title: Simple operation with lagged values
body: <p>I need to calculate line-wise simple operations using lagged values, for example the sum for a variable for the previous x years</p>
  <p>I tried:</p>
  <pre><code>toy %&gt;% 
    group_by(student) %&gt;% 
    mutate(lag_passed = sum(lag(passed, n = 5, order_by = year, default = 0)))
  
  toy %&gt;% 
    group_by(student) %&gt;% 
    arrange(year) %&gt;% 
    mutate(lag_passed = lapply(passed, function(x) sum(lag(x, n = 5, default = 0))))
  
  </code></pre>
  <p>Reproducible examples. Task sum the number of passed tests in the previous five years.</p>
  <pre><code>toy &lt;- data.frame(student = rep(&quot;A&quot;,10),
  year=c(1:10), 
  passed=c(0,0,0,1,2,0,0,0,0,1))
  
     student year passed
  1        A    1      0
  2        A    2      0
  3        A    3      0
  4        A    4      1
  5        A    5      2
  6        A    6      0
  7        A    7      0
  8        A    8      0
  9        A    9      0
  10       A   10      1
  
  expected &lt;- data.frame(student = rep(&quot;A&quot;,10),
  year=c(1:10), 
  passed=c(0,0,0,1,2,0,0,1,0,1), 
  lag_passed=c(0,0,0,0,1,3,3,3,4,3))
  
     student year passed lag_passed
  1        A    1      0          0
  2        A    2      0          0
  3        A    3      0          0
  4        A    4      1          0
  5        A    5      2          1
  6        A    6      0          3
  7        A    7      0          3
  8        A    8      1          3
  9        A    9      0          4
  10       A   10      1          3
  
  
  </code></pre>