title: 'Forward' cumulative sum in dplyr
body: <p>When examining datasets from longitudinal studies, I commonly get results like this from a <code>dplyr</code> analysis chain from the raw data:</p>
  
  <pre><code>df = data.frame(n_sessions=c(1,2,3,4,5), n_people=c(59,89,30,23,4))
  </code></pre>
  
  <p>i.e. a count of how many participants have completed a certain number of assessments at this point in time.</p>
  
  <p>Although it is useful to know how many people have completed <em>exactly n</em> sessions, we more often need to know how many have completed <em>at least n</em> sessions. As per the table below, a standard cumulative sum isn't appropriate, What we want are the values in the <code>n_total</code> column, which is a sort of "forwards cumulative sum" of the values in the <code>n_people</code> column. i.e. the value in each row should be the sum of the values of itself and all values beyond it, rather than the standard cumulative sum, which is the sum of all values up to and including itself:</p>
  
  <pre><code>n_sessions n_people  n_total  cumsum
           1       59      205      59
           2       89      146     148
           3       30       57     178
           4       23       27     201
           5        4        4     205
  </code></pre>
  
  <p>Generating the cumulative sum is simple:</p>
  
  <pre><code>mutate(df, cumsum = cumsum(n_people))
  </code></pre>
  
  <p>What would be an expression for generating a "forwards cumulative sum" that could be incorporated in a <code>dplyr</code> analysis chain? I'm guessing that <code>cumsum</code> would need to be applied to <code>n_people</code> after sorting by <code>n_sessions</code> descending, but can't quite get my head around how to get the answer while preserving the original order of the data frame. </p>