[R] Extracting Sequence Data from a Vector

David Winsemius dwinsemius at comcast.net
Wed Jun 10 20:01:21 CEST 2009


On Jun 10, 2009, at 1:28 PM, Eric Vander Wal wrote:

> Thanks in advance.
> I have a vector of numbers which contain sections that are sequences  
> which increase by a value of 1 followed by a gap in the data and  
> then another sequence occurs, etc:
>
> x<-c(1:3, 6: 7, 10:13)
>
> From the vector I need to extract 2 items of information A) the  
> first number in the sequence (e.g., 1, 6, 10) and B) how many  
> observations were in each  sequence section (e.g., 3, 2, 4).
>
> v1   v2
> 1      3
> 6      2
> 10    4
>
> It seems simple, but my R skills are still in their infancy so I  
> very much appreciate the help.
> Eric
>

Yet another solution:

 > x[which(c(-Inf, diff(x)) != 1)]
[1]  1  6 10

 > diff(c(which(c(-Inf, diff(x)) != 1), length(x)+1) )
[1] 3 2 4


-- 

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list