0

I'm relatively new when it comes to manipulating data with R. I want to create a new column in my data frame which creates a cumulative variable, I assume there's some way to do this with dplyR but am not too experienced with it. He's an example data frame.

Group  X   Y 
 A     0   0.00
 A     1   0.12
 A     4   0.02
 A     10  0.07
 A     17  0.41
 B     0   0.00
 B     3   0.06
 B     18  0.13
 B     25  0.20
 B     32  0.10

I want to create a column for a cumulative variable for Y in this case.

 Group  X   Y     cum_Y
 A     0   0.00   0.00
 A     1   0.12   0.12
 A     4   0.02   0.14
 A     10  0.07   0.21
 A     17  0.41   0.62
 B     0   0.00   0.00
 B     3   0.06   0.06
 B     18  0.13   0.19
 B     25  0.20   0.39
 B     32  0.10   0.49

Any help with an explanation would be much appreciated.

1 Answers1

0

Use cumsum by group:

libary(dplyr)
df %>%
   group_by(Group) %>%
   mutate(cum = cumsum(cum_Y))
Maël
  • 45,206
  • 3
  • 29
  • 67