title: dplyr / R cumulative sum with reset
body: <p>I'd like to generate cumulative sums with a reset if the "current" sum exceeds some threshold, using dplyr. In the below, I want to cumsum over 'a'.</p>
  
  <pre><code>library(dplyr)
  library(tibble)
  
  tib &lt;- tibble(
    t = c(1,2,3,4,5,6),
    a = c(2,3,1,2,2,3)
  )
  
  # what I want
  ## thresh = 5
  # A tibble: 6 x 4
  #         t     a     g     c
  #      &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt;
  #   1  1.00  2.00     0  2.00
  #   2  2.00  3.00     0  5.00
  #   3  3.00  1.00     1  1.00
  #   4  4.00  2.00     1  3.00
  #   5  5.00  2.00     1  5.00
  #   6  6.00  3.00     2  3.00
  
  # what I want
  ## thresh = 4
  # A tibble: 6 x 4
  #         t     a     g     c
  #      &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt;
  #   1  1.00  2.00     0  2.00
  #   2  2.00  3.00     0  5.00
  #   3  3.00  1.00     1  1.00
  #   4  4.00  2.00     1  3.00
  #   5  5.00  2.00     1  5.00
  #   6  6.00  3.00     2  3.00
  
  # what I want
  ## thresh = 6
  # A tibble: 6 x 4
  #         t     a     g     c
  #      &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt;
  #   1  1.00  2.00     0  2.00
  #   2  2.00  3.00     0  5.00
  #   3  3.00  1.00     0  6.00
  #   4  4.00  2.00     1  2.00
  #   5  5.00  2.00     1  4.00
  #   6  6.00  3.00     1  7.00
  </code></pre>
  
  <p>I've examined many of the similar questions here (such as <a href="https://stackoverflow.com/questions/44512075/resetting-cumsum-if-value-goes-to-negative-in-r">resetting cumsum if value goes to negative in r</a>) and have gotten what I hoped was close, but no.</p>
  
  <p>I've tried variants of</p>
  
  <pre><code>thresh &lt;-5
  tib %&gt;%
    group_by(g = cumsum(lag(cumsum(a) &gt;= thresh, default = FALSE))) %&gt;%
    mutate(c = cumsum(a)) %&gt;%
    ungroup()
  </code></pre>
  
  <p>which returns </p>
  
  <pre><code># A tibble: 6 x 4
        t     a     g     c
    &lt;dbl&gt; &lt;dbl&gt; &lt;int&gt; &lt;dbl&gt;
  1  1.00  2.00     0  2.00
  2  2.00  3.00     0  5.00
  3  3.00  1.00     1  1.00
  4  4.00  2.00     2  2.00
  5  5.00  2.00     3  2.00
  6  6.00  3.00     4  3.00
  </code></pre>
  
  <p>You can see that the "group" is not getting reset after the first time.</p>