1

I have a dataset like this:

ID  VAL
A   1
A   4
A   3
B   1
B   2
B   2

I want to add a column that gets me the cumulative sum of val per ID such as, preferably with Tidyverse functions, unless Base has something better.

ID  VAL CUM
A   1   8 
A   4   8
A   3   8
B   1   5
B   2   5
B   2   5

Thanks!

EGM8686
  • 1,492
  • 1
  • 11
  • 22

1 Answers1

3

Using dplyr, you can perform a sum on grouped ID

library(dplyr)
df =data.frame(ID = c(rep("A",3),rep("B",3)),
               VAL = c(1,4,3,1,2,2))

df %>% group_by(ID) %>% mutate(CUM = sum(VAL))

# A tibble: 6 x 3
# Groups:   ID [2]
  ID      VAL   CUM
  <fct> <dbl> <dbl>
1 A         1     8
2 A         4     8
3 A         3     8
4 B         1     5
5 B         2     5
6 B         2     5
dc37
  • 15,840
  • 4
  • 15
  • 32