Question

I'm hoping to compute a cumulative sum variable, but computed within levels of a given nesting variable. Here's some example data:

data <- data.frame(cbind(ids=c(rep(1,6),rep(2,4),rep(3,3)), values=c(1,5,2,7,3,5,1,6,2,4,1,6,3)))

I'm wanting a new vector that would look like this:

data$cumsum <- c(1,6,8,15,18,23,1,7,9,13,1,7,10)

With a final product like this:

> data
    ids values cumsum
1    1      1      1
2    1      5      6
3    1      2      8
4    1      7     15
5    1      3     18
6    1      5     23
7    2      1      1
8    2      6      7
9    2      2      9
10   2      4     13
11   3      1      1
12   3      6      7
13   3      3     10

Thanks!

Was it helpful?

Solution

You can use ave:

transform(data, cumsum = ave(values, ids, FUN = cumsum))

data
#   ids values cumsum
#1    1      1      1
#2    1      5      6
#3    1      2      8
#4    1      7     15
#5    1      3     18
#6    1      5     23
#7    2      1      1
#8    2      6      7
#9    2      2      9
#10   2      4     13
#11   3      1      1
#12   3      6      7
#13   3      3     10

Or using dplyr:

library(dplyr)
data %>% group_by(ids) %>% mutate(cumsum = cumsum(values))

OTHER TIPS

Should be faster with data.table for large datasets

library(data.table) 
setDT(data)[, Cumsum:=cumsum(values), by=ids]
data
#      ids values Cumsum
 # 1:   1      1      1
#  2:   1      5      6
#  3:   1      2      8
#  4:   1      7     15
#  5:   1      3     18
#  6:   1      5     23
#  7:   2      1      1
#  8:   2      6      7
#  9:   2      2      9
# 10:   2      4     13
# 11:   3      1      1
# 12:   3      6      7
# 13:   3      3     10
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top