[R] splitting a vector

Rui Barradas ruipbarradas at sapo.pt
Thu Aug 2 00:34:14 CEST 2012


Hello,

Try the following.


fun <- function(x){
     n.diff <- cumsum(diff(c(x[1], x)) <= 0)
     split(x, n.diff)
}

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

fun(  c(1,1,2,3,4,5,1,2,3,2,3,4,5,6,4,5) )

Hope this helps,

Rui Barradas
Em 01-08-2012 14:29, capy_bara escreveu:
> 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.
>
> ______________________________________________
> 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.



More information about the R-help mailing list