[R] Chopping a vector up into smaller vectors

Petr PIKAL petr.pikal at precheza.cz
Thu Aug 2 14:05:58 CEST 2012


Hi

one of possible options

f<- function(x, parts) split(x,rep(1:length(parts),parts))
f(9:1, c(3,2,4))
$`1`
[1] 9 8 7

$`2`
[1] 6 5

$`3`
[1] 4 3 2 1

You can also check if your parts vector agrees with x vector, if you want.

Regards
Petr


> 
> Anyone got a neat way to chop a vector up into smaller subvectors?
> This is what I have now, which seems inelegant:
> 
> chop <- function(v, counts) {
>   stopifnot(sum(counts)==length(v))
>   end <- cumsum(counts)
>   beg <- c(1, 1+end[-length(end)])
>   begend <- cbind(beg, end)
>   apply(begend, 1, function(x) v[x[1]:x[2]])
> }
> 
> 
> > chop(9:1, c(3,2,4))
> [[1]]
> [1] 9 8 7
> 
> [[2]]
> [1] 6 5
> 
> [[3]]
> [1] 4 3 2 1
> 
> ______________________________________________
> 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