Cumulative sum of a column based on the values of another column (R)

后端 未结 2 1787
野性不改
野性不改 2021-01-21 01:21

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         


        
相关标签:
2条回答
  • 2021-01-21 02:03

    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
    
    0 讨论(0)
  • 2021-01-21 02:19

    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
    
    0 讨论(0)
提交回复
热议问题