Skip to content

Chopping a vector up into smaller vectors

3 messages · Stephen Eglen, Eik Vettorazzi, PIKAL 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]])
}
[[1]]
[1] 9 8 7

[[2]]
[1] 6 5

[[3]]
[1] 4 3 2 1
#
Hi Stephen,
how about this:

chop<-function(x,counts){
 stopifnot(sum(counts)==length(x))
 split(9:1,unlist(mapply(rep,seq_along(counts),counts)))
}
chop(9:1,c(3,2,4))

cheers

Am 02.08.2012 12:29, schrieb Stephen Eglen:

  
    
#
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
http://www.R-project.org/posting-guide.html