Running sum on a column conditional on value

前端 未结 1 1666
春和景丽
春和景丽 2021-01-14 04:19

I have a vector of binary variables which state whether a product is on promotion in the period. I\'m trying to work out how to calculate the duration of each promotion and

相关标签:
1条回答
  • 2021-01-14 04:45

    It sounds like you need run length encoding (via the rle command in base R).

    unlist(sapply(rle(promo.flag)$lengths,seq))
    

    Gives you a vector 1 2 1 1 1 2 1 2 3 1 1 2 1. Not sure what you're going for with the zero at the end, but I assume it's a terminal condition and easy to change after the fact.

    This works because rle() returns a list of two, one of which is named lengths and contains a compact sequence of how many times each is repeated. Then seq when fed a single integer gives you a sequence from 1 to that number. Then apply repeatedly calls seq with the single numbers in rle()$lengths, generating a list of the mini sequences. unlist then turns that list into a vector.

    0 讨论(0)
提交回复
热议问题