title: Mutate a new column based on lagged values within that column - dplyr approach
body: <p>A base approach and dplyr were detailed here <a href="https://stackoverflow.com/questions/46668095/how-to-create-a-column-which-use-its-own-lag-value-using-dplyr">How to create a column which use its own lag value using dplyr</a></p>
  
  <p>I want the first row to equal k, and then every row subsequent to be the lag of "c" plus "a" minus "b".</p>
  
  <p>The base approach works.</p>
  
  <p>But the dplyr approach does not produce the same result as the base approach.
  See:
  </p>
  
  <pre class="lang-r prettyprint-override"><code>library(tidyverse)
  k &lt;- 10 # Set a k value
  df1 &lt;- tribble(
    ~a, ~b,
    1,  1,
    1,  2,
    1,  3,
    1,  4,
    1,  5,)
  # Base approach
  df1$c &lt;- df1$a - df1$b
  df1[1, "c"] &lt;- k
  df1$c &lt;- cumsum(df1$c)
  df1
  #&gt; # A tibble: 5 x 3
  #&gt;       a     b     c
  #&gt;   &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  #&gt; 1     1     1    10
  #&gt; 2     1     2     9
  #&gt; 3     1     3     7
  #&gt; 4     1     4     4
  #&gt; 5     1     5     0
  # New df
  df2 &lt;- tribble(
    ~a, ~b,
    1,  1,
    1,  2,
    1,  3,
    1,  4,
    1,  5,)
  # dplyr approach
  df2 %&gt;% 
    mutate(c = lag(cumsum(a - b), 
                   default = k))
  #&gt; # A tibble: 5 x 3
  #&gt;       a     b     c
  #&gt;   &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  #&gt; 1     1     1    10
  #&gt; 2     1     2     0
  #&gt; 3     1     3    -1
  #&gt; 4     1     4    -3
  #&gt; 5     1     5    -6
  # Gives two different dataframes
  </code></pre>
  
  <p><sup>Created on 2020-03-05 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v0.3.0)</sup></p>
  
  <p>Alternative code and desired output:
  </p>
  
  <pre class="lang-r prettyprint-override"><code>library(tidyverse)
  # Desired output
  tribble(
    ~a, ~b, ~c,
    1, 1, 10,
    1, 2, 9,
    1, 3, 7,
    1, 4, 4,
    1, 5, 0)
  #&gt; # A tibble: 5 x 3
  #&gt;       a     b     c
  #&gt;   &lt;dbl&gt; &lt;dbl&gt; &lt;dbl&gt;
  #&gt; 1     1     1    10
  #&gt; 2     1     2     9
  #&gt; 3     1     3     7
  #&gt; 4     1     4     4
  #&gt; 5     1     5     0
  df2 &lt;- tribble(
    ~a, ~b,
    1,  1,
    1,  2,
    1,  3,
    1,  4,
    1,  5,)
  k &lt;- 10
  df2 %&gt;% 
    mutate(c = case_when(
      row_number() == 1 ~ k,
      row_number() != 1 ~ lag(c) + a - b))
  #&gt; Error in x[seq_len(xlen - n)]: object of type 'builtin' is not subsettable
  </code></pre>
  
  <p><sup>Created on 2020-03-05 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v0.3.0)</sup></p>
  
  <p>Is there another tidyverse approach that provides the output of the base approach?</p>