tags:

views:

92

answers:

1

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 visit 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.

+9  A: 

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
unutbu
as an aside, a search in help for 'length of run' doesn't return rle. Someone's got to update that help file so that it includes that phrase ("run length" does work).
John