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

前端 未结 3 734
粉色の甜心
粉色の甜心 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:26

    I think this is best done with a for loop, can't think of a function that could do so out of the box. The following should do what you want (if I understand you correctly).

    current.sum <- 0
    for (c in 1:nrow(caribou.sub)) {
        current.sum <- current.sum + caribou.sub[c, "difference"]
        carribou.sub[c, "difference_sum"] <- current.sum
        if (current.sum >= 1470) {
            caribou.sub[c, "keep"] <- 1
            current.sum <- 0
        }
    }
    

    Feel free to comment if it does not exactly what you want. But as pointed out by alexwhan, your description is not completely clear.

提交回复
热议问题