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
Try the ggplot2 function,
cut_number
:I need a function that takes the argument of a data.table (in quotes) and another argument that is the upper limit on the number of rows in the subsets of that original data.table. This function produces whatever number of data.tables that upper limit allows for:
This function gives me a series of data.tables named df_[number] with the starting row from the original data.table in the name. The last data.table can be short and filled with NAs so you have to subset that back to whatever data is left. This type of function is useful because certain GIS software have limits on how many address pins you can import, for example. So slicing up data.tables into smaller chunks may not be recommended, but it may not be avoidable.
Simple function for splitting a vector by simply using indexes - no need to over complicate this
Yet another possibility is the
splitIndices
function from packageparallel
:Gives:
This will split it differently to what you have, but is still quite a nice list structure I think:
Which will give you the following, depending on how you want it formatted:
Running a couple of timings using these settings:
Then we have the following results:
EDIT: Changing from as.factor() to as.character() in my function made it twice as fast.
I needed the same function and have read the previous solutions, however i also needed to have the unbalanced chunk to be at the end i.e if i have 10 elements to split them into vectors of 3 each, then my result should have vectors with 3,3,4 elements respectively. So i used the following (i left the code unoptimised for readability, otherwise no need to have many variables):