Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cumulative sum through years R

I would like to obtain a cumulative sum through years and for each entity.

Here below an example, and what I have tried so far:

data<-data.frame(id=c("a","a","a","b","a","b","b"),cars=c(1,1,1,1,1,1,1),year=c(2001,2001,2002,2003,2003,2003,2004))

I have tried :

library(tidyverse)
library(stringr)
library(dplyr)
library(tidyr)

data %>% group_by(id,year) %>% mutate(csum = (cumsum(cars))) %>% top_n(1, csum)
  id     cars  year  csum
  <chr> <dbl> <dbl> <dbl>
1 a         1  2001     2
2 a         1  2002     1
3 a         1  2003     1
4 b         1  2003     2
5 b         1  2004     1

This is what I would like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  id     cars  year  csum
  <chr> <dbl> <dbl> <dbl>
1 a         1  2001     2
2 a         1  2002     3
3 a         1  2003     4
4 b         1  2003     2
5 b         1  2004     3

Thank you very much.

>Solution :

The function you need is aggregate, you can use it this way :

aggregate(x=data$cars, #column on which you want to apply a function
          by=list(id=data$id,year=data$year),#grouping variables
          FUN=sum)#function to apply
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading