[R] Chopping a vector up into smaller vectors
Stephen Eglen
S.J.Eglen at damtp.cam.ac.uk
Thu Aug 2 12:29:31 CEST 2012
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
More information about the R-help
mailing list