[R] Finding indices where
Petr Pikal
petr.pikal at precheza.cz
Thu May 20 10:28:34 CEST 2004
On 19 May 2004 at 13:26, Ravi Varadhan wrote:
> Hi:
>
> Suppose I have the following vector:
>
> > x <- c(1,4:8,11,13:14,17,19,23:28,35:38)
> > x
> [1] 1 4 5 6 7 8 11 13 14 17 19 23 24 25 26 27 28 35 36 37 38 >
>
>
> and I would like to pick out the first and last indices of all the
> consecutive "runs" of integers, where the length of a run is no
> smaller than a specified value, say, nmin. That is, in the above
> example, for nmin=4, I would like to get the following 3 by 2 matrix:
>
> 4 8
> 23 28
> 35 38
>
> For nmin=5, I would get the following 2 by 2 matrix
>
> 4 8
> 23 28
>
> and for nmin=6, I would get the following 1 by 2 matrix
>
> 23 28
>
> Is there an efficient and elegant way to do this?
Hallo
not complete maybe not ellegant but
y<-rle(diff(x))
res1<-x[(cumsum(y$length))[y$length>1]]+1
res2<-res1-y$length[y$length>1]
gives you the numbers you want in two vectors (res1, res2). Than you can do
any formating and selection you want.
Cheers
Petr
>
> Thanks very much for any help/suggestions.
> Ravi.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
Petr Pikal
petr.pikal at precheza.cz
More information about the R-help
mailing list