[R] splitting a vector
William Dunlap
wdunlap at tibco.com
Thu Aug 2 00:41:42 CEST 2012
The following 'f' counts the number of times the sequence x
does not increase. Is this what you want?
> f <- function(x) split(x, cumsum(c(TRUE, x[-1] <= x[-length(x)])))
> f(numbers)
$`1`
[1] 1 2
$`2`
[1] 1 2 3 4 5
> f(c(1,1,2,3,4,5,1,2,3,2,3,4,5,6,4,5))
$`1`
[1] 1
$`2`
[1] 1 2 3 4 5
$`3`
[1] 1 2 3
$`4`
[1] 2 3 4 5 6
$`5`
[1] 4 5
Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of capy_bara
> Sent: Wednesday, August 01, 2012 6:30 AM
> To: r-help at r-project.org
> Subject: [R] splitting a vector
>
> 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