开发者

How do I calculate the length of consecutive runs of events, e.g. wins, visits, in R

I have a set of days-each with a 0/1 code- for the presence of an event I will call 'visit.'

For example for day 1 to day 12 I could have the vector (0,0,1,0,1,1,1,1,0,0,0,1) when I have a vis开发者_运维百科it on days 3,5,6,7,8, and 12. I would like to apply some function that will give me the vector (1,4,1) which will imply 3 groups of visits of duration of 1, 4 and 1 day. It is easy to find the 0s. I can't figure out to combine the lags and cumulative sums to get a 1 day visit or an extended visit.


Perhaps use rle:

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

runs=rle(x)
Run Length Encoding
  lengths: int [1:6] 2 1 1 4 3 1
  values : num [1:6] 0 1 0 1 0 1

runs$lengths[runs$values!=0]
[1] 1 4 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜