Predictive Hacks

How to Split a Vector into Equal Parts in R

We will show you how to split an R vector into n parts of equal size. Bear in mind that sometimes is not possible to create chunks of equal size. For example, if we want each part to consist of 3 elements and our vector has 21 elements, then it is possible to create 7 chunks of 3 elements. But if the vector has 23 elements, then we will need to create 7 chunks of 3 elements and 1 chunk of 2 elements. Let’s get our hands dirty.

# set a random seed
set.seed(5)

# elements of each part
k<-3

# generate 23 values from poisson distribution 
# with parameter lambda = 20
x<-rpois(23, lambda = 20)

# split the vector 
split_vector<-split(x, ceiling(seq_along(x)/k))

# print
split_vector
$`1`
[1] 16 17 20

$`2`
[1] 27 17 20

$`3`
[1] 16 20 25

$`4`
[1] 16 19 28

$`5`
[1] 27 22 24

$`6`
[1] 24 26 23

$`7`
[1] 23 18 26

$`8`
[1] 26 17

As we can see, we generated 8 chunks, where the last one is of 2 elements and all the rest of 3. Finally, since the output is a list, we can retrieve each chunk as follows.

# get the third chunk
split_vector[[3]]
[1] 16 20 25

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s