Articles - Tips & Tricks

dplyr: How to Add Cumulative Sums by Groups Into a Data Frame?

  |   84153  |  Post a comment  |  Tips & Tricks  |  dplyr, Tips & Tricks
To add into a data frame, the cumulative sum of a variable by groups, the syntax is as follow using the dplyr package and the iris demo data set:

Code R :
 
library(dplyr)
iris %>%
  group_by(Species) %>%
  mutate(cum_sep_len = cumsum(Sepal.Length))
 


Output:

# A tibble: 150 x 6
# Groups:   Species [3]
   Sepal.Length Sepal.Width Petal.Length Petal.Width Species cum_sep_len
                                         
 1          5.1         3.5          1.4         0.2  setosa         5.1
 2          4.9         3.0          1.4         0.2  setosa        10.0
 3          4.7         3.2          1.3         0.2  setosa        14.7
 4          4.6         3.1          1.5         0.2  setosa        19.3
 5          5.0         3.6          1.4         0.2  setosa        24.3
 6          5.4         3.9          1.7         0.4  setosa        29.7
 7          4.6         3.4          1.4         0.3  setosa        34.3
 8          5.0         3.4          1.5         0.2  setosa        39.3
 9          4.4         2.9          1.4         0.2  setosa        43.7
10          4.9         3.1          1.5         0.1  setosa        48.6
# ... with 140 more rows