[R] splitting a vector

capy_bara hettling at few.vu.nl
Wed Aug 1 15:29:55 CEST 2012


Hello,

I have a vector with positive integer numbers, e.g. 

> numbers <- c(1,2,1,2,3,4,5)

and want to split the vector whenever an element in the vector is smaller or
equal to its predecessor. 
Hence I want to obtain two vectors: c(1,2) and c(1,2,3,4,5).
I tried with which(), but it is not so elegant:

> numbers[1:(which(numbers<=numbers[1])[2]-1)]
> numbers[which(numbers<=numbers[1])[2]:length(numbers)]

Sure I can do it with a for-loop, but that seems a bit tedious for that
small problem. 
Does maybe anyone know a simple and elegant solution for this? I'm searching
for a general solution, since
my vector may change and maybe be split into more than two vectors, e.g.
give five vectors for c(1,1,2,3,4,5,1,2,3,2,3,4,5,6,4,5).

Many thanks in advance,

Hannes







--
View this message in context: http://r.789695.n4.nabble.com/splitting-a-vector-tp4638675.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list