0 votes
1 view
in R Programming by (6.5k points)

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 somewhere.

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

1 Answer

0 votes
by (25.3k points)

To split a vector into chunks you can use the following methods:

df = rpois(100,5)

df

df

  [1]  3  4  3  8  0  5  9  3  3  1 12  7  6  6  5  4  5  7  6  3  9  6  6  4  2  4  6  5

 [29]  4  6  9  5  4  3  4  3  2  4  5  3  5  4  6  6  5  5  3  5  6  5  5  5  3  7  7  3

 [57]  4  3  1  2  4  5  5 13  4  5  3  9  2  4  7  7  2  5  3  6  3  6  1  6  0  4  4  4

 [85]  7  5  5  6  8  6  5  1  7  8  5  3  5  7  7  3

To split the above data frame into 4 chunks of size 25:

max <- 25

x <- seq_along(df)

df <- split(df, ceiling(x/max))

df

$`1`

 [1]  3  4  3  8  0  5  9  3  3  1 12  7  6  6  5  4  5  7  6  3  9  6  6  4  2

$`2`

 [1] 4 6 5 4 6 9 5 4 3 4 3 2 4 5 3 5 4 6 6 5 5 3 5 6 5

$`3`

 [1]  5  5  3  7  7  3  4  3  1  2  4  5  5 13  4  5  3  9  2  4  7  7  2  5  3

$`4`

 [1] 6 3 6 1 6 0 4 4 4 7 5 5 6 8 6 5 1 7 8 5 3 5 7 7 3

OR

x <-  rpois(100,5)

 

n = 4

 split(x, sort(x%%n))

$`0`

 [1] 6 6 2 7 3 5 9 8 7 3 8 1 5 2 3 3 3 4 7

$`1`

 [1] 7 7 2 5 6 5 6 6 5 1 9 5 7 7 3 4 9 3 3 4 6 7 8 4 6 4 5

$`2`

 [1] 7 9 4 3 5 4 6 6 6 9 2 6 6 4 3 7 5 7 8 3 4 5 6 5

$`3`

 [1] 7 7 2 6 4 3 4 2 8 3 6 5 6 9 7 5 4 9 4 3 4 3 5 6 5 3 5 6 5 9

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...