-2

I have a data frame that looks like this :

> year<-c(2014,2014,2014,2015,2015,2015,2016,2016,2016)
> group<-c("A","B","C","A","B","C","A","B","C")
> n<-c(1,1,1,1,2,0,2,1,1)
> df<-data.frame(year=year,group=group,n=n)
> df

year group n
2014     A 1
2014     B 1
2014     C 1
2015     A 1
2015     B 2
2015     C 0
2016     A 2
2016     B 1
2016     C 1

I want to create a column that contains the cumulated values of n for each group to have something like this :

year group n  sum
2014     A 1  1
2014     B 1  1
2014     C 1  1
2015     A 1  2
2015     B 2  3
2015     C 0  1
2016     A 2  4
2016     B 1  4
2016     C 1  2

1 Answers1

1

We can use one of the group by functions. With data.table, convert the 'data.frame' to 'data.table' (setDT(df1), group by 'group', we assign (:=) the cumsum(n) as the "Sum" column.

library(data.table)
setDT(df1)[, Sum:= cumsum(n),group]

Or with base R, we can do this with ave.

 df1$Sum <- with(df1, ave(n, group, FUN=cumsum))
akrun
  • 874,273
  • 37
  • 540
  • 662