title: Cumulative sum with potential "resets"
body: <p>I have a numeric vector for which I want to calculate a sort of cumulative sum. I say "a sort" because a standard cumsum is basically <code>cumsum[i] = cumsum[i-1] + x[i]</code>. In this case, however, I need to use <code>cumsum[i] = max(cumsum[i-1] + x[i], x[i])</code>.</p>
  
  <p>That is, if the value of the most recent element is greater than the cumulative sum (which can happen if there were previous negative values, for example), then simply adopt the most recent element.</p>
  
  <p>This can obviously be done manually with a trivial for-loop:</p>
  
  <pre class="lang-r prettyprint-override"><code>set.seed(1)
  x &lt;- runif(10, min = -1, max = 1)
  csum &lt;- rep(0, 10)
  for(i in seq_along(x)) {
    if (i == 1) csum[i] &lt;- x[i]
  
    csum[i] &lt;- max(csum[i-1] + x[i], x[i])
  }
  x; csum
  #&gt;  [1] -0.4689827 -0.2557522  0.1457067  0.8164156 -0.5966361  0.7967794
  #&gt;  [7]  0.8893505  0.3215956  0.2582281 -0.8764275
  #&gt;  [1] -0.4689827 -0.2557522  0.1457067  0.9621223  0.3654862  1.1622655
  #&gt;  [7]  2.0516161  2.3732117  2.6314397  1.7550123
  </code></pre>
  
  <p><sup>Created on 2020-04-27 by the <a href="https://reprex.tidyverse.org" rel="nofollow noreferrer">reprex package</a> (v0.3.0)</sup></p>
  
  <p>But is there a way of doing this which avoids a for-loop? I've been banging my head trying to think of one but just can't.</p>
  
  <p>If relevant, my real case will apply this to a dataframe. It will be grouped, and then I'll create a new column with this cumulative sum for each group. But I'm comfortable with that part, I just can't figure out how to clean up this operation.</p>