[R] Search for longest consecutive occurrence

Gabor Grothendieck ggrothendieck at gmail.com
Sat May 23 19:17:42 CEST 2009


Try this:

with(rle(test), max(lengths[!!values]))


On Sat, May 23, 2009 at 1:09 PM, tsunhin wong <thjwong at gmail.com> wrote:
> Dear R Users,
>
> I am trying to write a script to count the longest consecutive
> occurring 1 in a sequence:
> test<-c(1,1,1,1,1,1,1,0,0,0,0,1,1,0,1,0,1,0,1,1)
>
> In the case of the object "test", 1 occurs 7 consecutive times which
> is the longest consecutive within the sequence.
> I know I can always do a thorough from start to end search and use a
> counter to count.
> But, do you know there can be a smarter way to achieve this in R?
>
> Thanks a lot!
>
> - John
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list