I have to split a vector into n chunks of equal size in R. I couldn't find any base function to do that. Also Google didn't get me anywhere. So here is what I came up with, hopefully it helps someone some where.
x <- 1:10
n <- 3
chunk <- function(x,n) split(x, factor(sort(rank(x)%%n)))
chunk(x,n)
$`0`
[1] 1 2 3
$`1`
[1] 4 5 6 7
$`2`
[1] 8 9 10
Any comments, suggestions or improvements are really welcome and appreciated.
Cheers, Sebastian
If you don't like
split()
and you don't likematrix()
(with its dangling NAs), there's this:Like
split()
, it returns a list, but it doesn't waste time or space with labels, so it may be more performant.