Home » How to Split a Vector into Chunks in R

How to Split a Vector into Chunks in R

by Erma Khan
spot_img

You can use the following basic syntax to split a vector into chunks in R:

chunks 4, labels=FALSE))

This particular example splits the vector called my_vector into 4 equally sized chunks.

To split the vector into a different number of chunks, simply change the 4 to a different value.

The following example shows how to use this syntax in practice.

Example: Splitting a Vector into Chunks in R

Suppose we have the following vector in R that contains 12 total elements:

#create vector
my_vector #view length of vector
length(my_vector)

[1] 12

We can use the following syntax to split the vector into four chunks:

#split vector into four chunks
chunks 4, labels=FALSE))

#view chunks
chunks

$`1`
[1] 2 2 4

$`2`
[1] 7 6 8

$`3`
[1] 9 8 8

$`4`
[1] 12  5  4

From the output we can see:

  • The first chunk contains the values 2, 2, 4.
  • The second chunk contains the values 7, 6, 8.
  • The third chunk contains the values 9, 8, 8.
  • The fourth chunk contains the values 12, 5, 4.

Note that we can also use brackets to access a specific chunk:

#access second chunk only
chunks[2]

$`2`
[1] 7 6 8

If we change the value within the split() function, we can split the vector into a different number of chunks.

For example, we could split the vector into six chunks instead:

#split vector into six chunks
chunks 6, labels=FALSE))

#view chunks
chunks

$`1`
[1] 2 2

$`2`
[1] 4 7

$`3`
[1] 6 8

$`4`
[1] 9

$`5`
[1] 8 8

$`6`
[1] 12  5

Notice that there are now six chunks and each chunk contains two elements.

Note: If your vector doesn’t contain an even number of elements, this method will still split the vector into as equally-sized groups as possible.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Filter a Vector in R
How to Remove NA Values from Vector in R
How to Remove Specific Elements from Vector in R

spot_img

Related Posts