[R] splitting a vector

Jan van der Laan rhelp at eoos.dds.nl
Thu Aug 2 10:45:35 CEST 2012


I come up with:

runs <- function(numbers) {
     tmp <- diff(c(0, which(diff(numbers) <= 0), length(numbers)))
     split(numbers, rep(seq_along(tmp), tmp))
}



Can't say it's elegant, but it seems to work

> runs(c(1:3, 1:4))
$`1`
[1] 1 2 3

$`2`
[1] 1 2 3 4

> runs(c(1,1,1))
$`1`
[1] 1

$`2`
[1] 1

$`3`
[1] 1

> runs(c(1:3, 2:3, 3))
$`1`
[1] 1 2 3

$`2`
[1] 2 3

$`3`
[1] 3


HTH,

Jan



capy_bara <hettling at few.vu.nl> schreef:

> 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