[R] identifying a 'run' in a vector

Joshua Wiley jwiley.psych at gmail.com
Thu Jul 7 02:25:48 CEST 2011


I seem to recall seeing this done in one or two elegant lines, but....

run <- function(x, type = 1) {
  index <- rle(diff(c(NA, x)))
  i <- cumsum(index$lengths)
  j <- match(type, index$values)
  x[seq.int(i[j - 1], i[j])]
}

run(c(1, 2, 3, 4, 5, 6, 7, 8, 20, 21, 22, 45))
run(c(20, 22, 24, 26, 1, 2, 3, 4, 5, 6, 7, 8, 20, 21, 22, 45))
run(c(NA, 20, 24, 28, 23:30))
run(c(20, 22, 24, 26, 1, 2, 3, 4, 5, 6, 7, 8, 20, 21, 22, 45), type = 2)

Cheers,

Josh

On Wed, Jul 6, 2011 at 4:49 PM, B77S <bps0002 at auburn.edu> wrote:
>
> well.. the following works, but if you have another idea I am still
> interested.
>
> 1:(which(diff(x)!=1)[1])
>
>
>
>
>
>
>
> B77S 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-tp3650295p3650318.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