3

I have a data frame with 2 columns like this:

> data.frame(x=1:10, y=c(0,0,0,1,1,0,0,1,0,1))
    x y
1   1 0
2   2 0
3   3 0
4   4 1
5   5 1
6   6 0
7   7 0
8   8 1
9   9 0
10 10 1

and I want to get the cumulative sum of column x (cumsum(df$x)), but the sum should be reset after a 1 appears in column y. This is the result I am looking for:

1
3
6
10
5
6
13
21
9
19

How can I achieve this in R?

Sven Hohenstein
  • 78,180
  • 16
  • 134
  • 160
SKp
  • 45
  • 5

2 Answers2

4

You can achieve that by using ave:

ave(d$x,c(0,cumsum(d$y[-nrow(d)])),FUN=cumsum)

#  [1]  1  3  6 10  5  6 13 21  9 19
Marat Talipov
  • 12,654
  • 4
  • 33
  • 51
3

A data.table method using shift

 library(data.table) #devel version `data.table_1.9.5` 
 setDT(d)[, cumsum(x), by = cumsum(shift(y, fill=0))]$V1
 #[1]  1  3  6 10  5  6 13 21  9 19
Arun
  • 113,200
  • 24
  • 277
  • 373
akrun
  • 789,025
  • 32
  • 460
  • 575