Skip to content

Instantly share code, notes, and snippets.

@tomhopper
Last active August 7, 2020 17:39
Show Gist options
  • Save tomhopper/857d08681251f93f507979ef2fe1cb83 to your computer and use it in GitHub Desktop.
Save tomhopper/857d08681251f93f507979ef2fe1cb83 to your computer and use it in GitHub Desktop.
Add a cumulative sum column to a data frame using dplyr
df %>%
group_by(id) %>%
mutate(cumsum = cumsum(value)) %>%
ungroup()
# from \url{http://stackoverflow.com/a/21818500/393354}
@IamKDO
Copy link

IamKDO commented Feb 24, 2019

Does not workks

@tomhopper
Copy link
Author

Fixed.

@westland
Copy link

westland commented Aug 6, 2020

Does not work (Aug 6, 2020)

@tomhopper
Copy link
Author

@westland It works for me. Try:

library(tidyverse)
data_df <- tibble(id = sample(letters[1:4], 15,
                   replace = TRUE),
       value = runif(15))

data_df %>% 
  group_by(id) %>% 
  mutate(cs = cumsum(value)) %>% 
  ungroup() %>% 
  arrange(id)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment