[R] Finding "runs" of TRUE in binary vector

Sean Davis sdavis2 at mail.nih.gov
Thu Jan 27 23:37:28 CET 2005


Thanks Patrick, Albyn, and Vadim.

rle() does what I want and, Vadim, your method gives the same results 
in a different form.  I appreciate the help!

Sean

On Jan 27, 2005, at 5:29 PM, Vadim Ogranovich wrote:

> Untested:
>
> c(TRUE, b[-1] != b[-length(b)]) gives you the (logical) indexes of the
> beginnings of the runs
> c(b[-1] != b[-length(b)], TRUE) gives you the (logical) indexes of the
> ends of the runs
>
>> -----Original Message-----
>> From: r-help-bounces at stat.math.ethz.ch
>> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Sean Davis
>> Sent: Thursday, January 27, 2005 2:14 PM
>> To: r-help
>> Subject: [R] Finding "runs" of TRUE in binary vector
>>
>> I have a binary vector and I want to find all "regions" of
>> that vector that are runs of TRUE (or FALSE).
>>
>>> a <- rnorm(10)
>>> b <- a<0.5
>>> b
>>   [1]  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE
>>
>> My function would return something like a list:
>> region[[1]] 1,3
>> region[[2]] 5,5
>> region[[3]] 7,10
>>
>> Any ideas besides looping and setting start and ends directly?
>>
>> Thanks,
>> Sean
>>
>> ______________________________________________
>> R-help at stat.math.ethz.ch mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide!
>> http://www.R-project.org/posting-guide.html
>>




More information about the R-help mailing list