Cumulative sum for positive numbers only

前端 未结 9 1216
梦谈多话
梦谈多话 2020-12-09 08:13

I have this vector :

x = c(1,1,1,1,1,0,1,0,0,0,1,1)

And I want to do a cumulative sum for the positive numbers only. I should have the fol

9条回答
  •  情话喂你
    2020-12-09 08:42

    Here is another base R solution using aggregate. The idea is to make a data frame with x and a new column named x.1 by which we can apply aggregate functions (cumsum in this case):

    x <- c(1,1,1,1,1,0,1,0,0,0,1,1)
    r <- rle(x)
    df <- data.frame(x, 
    x.1=unlist(sapply(1:length(r$lengths), function(i) rep(i, r$lengths[i]))))
    
    # df
    
       # x x.1
    # 1  1   1
    # 2  1   1
    # 3  1   1
    # 4  1   1
    # 5  1   1
    # 6  0   2
    # 7  1   3
    # 8  0   4
    # 9  0   4
    # 10 0   4
    # 11 1   5
    # 12 1   5
    
    agg <- aggregate(df$x~df$x.1, df, cumsum)
    as.vector(unlist(agg$`df$x`))
    
    # [1] 1 2 3 4 5 0 1 0 0 0 1 2
    

提交回复
热议问题