Cumulative sum until maximum reached, then repeat from zero in the next row

前端 未结 3 726
粉色の甜心
粉色の甜心 2020-11-28 14:07

I feel like this is a fairly easy question, but for the life of me I can\'t seem to find the answer. I have a fairly standard dataframe, and what I am trying to do is sum th

3条回答
  •  [愿得一人]
    2020-11-28 14:33

    I still don't understand about when the sum should restart and if it should be zero then. A desired result would help greatly.

    Nonetheless, I can't help but think that simply indexing and subtraction would be a straightforward way of doing this. The below code gives the same result as @Henrik's solution.

    df$difference_sum <- cumsum(df$difference)
    step <- (df$difference_sum %/% 1470) + 1
    k <- which(diff(step) > 0) + 1
    df$keep <- 0
    df$keep[k] <- 1
    step[k] <- step[k] - 1
    df$difference_sum <- df$difference_sum - c(0, df$difference_sum[k])[step]
    

提交回复
热议问题