Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 598
Georgette Avatar asked Jun 03 '10 18:06

Georgette


1 Answers

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
like image 142
unutbu Avatar answered Nov 24 '22 09:11

unutbu