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
A few more variants to the pile...
Note, that you don't need to use the
factor
function here, but you still want tosort
o/w your first vector would be1 2 3 10
:Or you can assign character indices, vice the numbers in left ticks above:
Or you can use plainword names stored in a vector. Note that using
sort
to get consecutive values inx
alphabetizes the labels:A one-liner splitting d into chunks of size 20:
More details: I think all you need is
seq_along()
,split()
andceiling()
:If you don't like
split()
and you don't mind NAs padding out your short tail:The columns of the returned matrix ([,1:ncol]) are the droids you are looking for.
Using base R's
rep_len
:And as already mentioned if you want sorted indices, simply: