[R] identifying a 'run' in a vector

Joshua Wiley jwiley.psych at gmail.com
Thu Jul 7 01:46:53 CEST 2011


Hi,

If an "ordered run" means the difference is between the ith and ith +
1 position is 1, then:

out <- rle(diff(x))

?diff gives you the differences (i + 1) - (i), and then run length
encoding encodes how long a run of the same number is.  In this case,
there first run is length 7.

rle() outputs a list.  If you only want to consider runs that change
by 1, then use the "values" element of the list to select only those

out$values == 1

if it is not at the beginning of the vector, cumsum(out$lengths) can
help to find the right indices to extract your run.

Hope this helps,

Josh

On Wed, Jul 6, 2011 at 4:32 PM, B77S <bps0002 at auburn.edu> wrote:
> Hi,
>
> How can I discern which elements in x (see below) are in 'order', but more
> specifically.. only the 1st 'ordered run'?
> I would like for it to return elements 1:8... there may be ordered values
> after 1:8, but those are not of interest.
>
> x <- c(1, 2, 3, 4, 5, 6, 7, 8, 20, 21, 22, 45)
>
>
> Thanks for any suggestions.
>
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/identifying-a-run-in-a-vector-tp3650295p3650295.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
https://joshuawiley.com/



More information about the R-help mailing list