As there were many good answers, I benchmarked the solutions that worked properly:
![Microbenchmark result for "split in chunks" solutions](https://cdn.statically.io/img/i.sstatic.net/194gvkC3.png)
Below, the code:
require(microbenchmark)
require(ggplot2)
require(parallel)
x <- rpois(75,5)
result <- microbenchmark(times = 1000,
"Harlan" = split(x, ceiling(seq_along(x)/(length(x)/5))),
"mathheadinclouds" = split(x, cut(seq_along(x), 5, labels = FALSE)),
"Richard DiSalvo on zhan2383" = split(x, sort(1:length(x) %% 5)),
"FXQuantTrader" = split(x, sort(rep_len(1:5, length(x)))),
"verbamour" = {mapply(function(a, b) (x[a:b]), seq.int(from=1, to=length(x), by=floor(length(x)/5)),
pmin(seq.int(from=1, to=length(x), by=floor(length(x)/5))+floor((length(x)/5-1)), length(x)),
SIMPLIFY=FALSE)},
"Tony Breyal" = chunk.2(x, 5),
"Richard Herron" = split(x, sort(rep(letters[1:5], each=5, len=length(x)))),
"Philip Michaelsen" = vsplit(x, 5),
"Iyar Lin" = split_to_chunks(x, 5)
)
split_to_chunks <- function(x, n, keep.order=TRUE){
if(keep.order){
return(split(x, sort(rep(1:n, length.out = length(x)))))
}else{
return(split(x, rep(1:n, length.out = length(x))))
}
}
vsplit <- function(v, n) {
l = length(v)
r = l/n
return(lapply(1:n, function(i) {
s = max(1, round(r*(i-1))+1)
e = min(l, round(r*i))
return(v[s:e])
}))
}
x <- c(NA, 4, 3, NA, NA, 2, 1, 1, NA ); y <- letters[x]; z <- factor(y)
gives examples with missing data, repeated values, that are not already sorted, and are in different classes (integer, character, factor).