title: How to calculate cumulative values within a column
body: <p>I'm trying to calculate the cumulative time among several grades.</p>
  <p>Here's how my original <code>df</code> looks like:</p>
  <pre><code>df = data.frame(id = c(1,1,1,1,2,2,2,2),
                  group = c(0,0,0,0,1,1,1,1),
                  grade = c(0,1,2,3,0,1,3,4),
                  time = c(10,7,4,1,20,17,14,11))
  </code></pre>
  <p>Here's what I'm expecting as the result <code>df1</code>:</p>
  <pre><code>df1 = df %&gt;%
    pivot_wider(
      names_from = &quot;grade&quot;,
      names_prefix = &quot;grade_&quot;,
      values_from = &quot;time&quot;) %&gt;%
    replace(is.na(.), 0) %&gt;%
    
    mutate(grade_1 = grade_1 + grade_2 + grade_3 + grade_4,
           grade_2 = grade_2 + grade_3 + grade_4,
           grade_3 = grade_3 + grade_4) %&gt;%
    
    pivot_longer(
      cols = 3:7,
      names_to = &quot;grade&quot;,
      names_prefix = &quot;grade_&quot;,
      values_to = &quot;time&quot;) 
  </code></pre>
  <p>My method works, but I want it to be more flexible. When I have more grades in the df, I don't need to manually add grade_x = grade_1 + grade_2 + grade_3 ...</p>
  <p>Thank you!</p>