# How to split a vector into chunks in R?

R ProgrammingServer Side ProgrammingProgramming

This can be done with the help of seq_along, split, and ceiling.

## Example

> x <- rpois(100,5)
> x
[1] 6 5 6 3 11 4 5 6 7 4 6 4 3 4 7 1 8 4 2 4 5 7 8 5 9
[26] 3 5 5 5 1 7 5 8 1 8 3 8 4 5 7 5 8 4 4 2 5 6 3 9 4
[51] 6 3 3 2 5 6 5 4 5 5 2 3 3 12 11 6 4 5 6 7 5 2 2 5 8
[76] 3 8 8 7 3 7 6 6 4 1 6 8 3 6 6 6 6 4 8 6 4 5 4 2 5
> max <- 20
> y <- seq_along(x)
> chunks <- split(x, ceiling(y/max))
> chunks
$1 [1] 6 5 6 3 11 4 5 6 7 4 6 4 3 4 7 1 8 4 2 4$2
[1] 5 7 8 5 9 3 5 5 5 1 7 5 8 1 8 3 8 4 5 7
$3 [1] 5 8 4 4 2 5 6 3 9 4 6 3 3 2 5 6 5 4 5 5$4
[1] 2 3 3 12 11 6 4 5 6 7 5 2 2 5 8 3 8 8 7 3
\$5
[1] 7 6 6 4 1 6 8 3 6 6 6 6 4 8 6 4 5 4 2 5
Published on 06-Jul-2020 14:36:11