Sessionize a sequence of numbers into groups that reset once a cumulative threshold is met

前端 未结 1 698
天命终不由人
天命终不由人 2021-01-27 22:40

Consider this sequence, which we can think of as \"time between events\"

x <- c(5, 40, 3, 6, 0, 9, 0, 4, 5, 18, 2, 4, 3, 2)

I would like to group

相关标签:
1条回答
  • 2021-01-27 23:02

    One option is to use Reduce() to calculate the cumulative sum where you can set the sum to be zero, when it exceeds some threshold:

    cumsum(Reduce(function(x, y) if(x < 30) x + y else y, x, acc = T) >= 30)
    # [1] 0 1 1 1 1 1 1 1 1 2 2 2 2 2
    
    0 讨论(0)
提交回复
热议问题