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
You could combine the split/cut, as suggested by mdsummer, with quantile to create even groups:
This gives the same result for your example, but not for skewed variables.
Sorry if this answer comes so late, but maybe it can be useful for someone else. Actually there is a very useful solution to this problem, explained at the end of ?split.
split(x,matrix(1:n,n,length(x))[1:length(x)])
perhaps this is more clear, but the same idea:
split(x,rep(1:n, ceiling(length(x)/n),length.out = length(x)))
if you want it ordered,throw a sort around it
Credit to @Sebastian for this function
Here's another variant.
NOTE: with this sample you're specifying the CHUNK SIZE in the second parameter
Wow, this question got more traction than expected.
Thanks for all the ideas. I have come up with this solution:
The key is to use the seq(each = chunk.size) parameter so make it work. Using seq_along acts like rank(x) in my previous solution, but is actually able to produce the correct result with duplicate entries.