Open In App

Split Vector into Chunks in R

In this article, we will discuss how to split vectors into chunks in R programming language.

Method 1: By using the length of each chunk

In this scenario, a chuck length is specified, so that we can divide the vector using the split() function.



Syntax:

split(vector,   ceiling(seq_along(vector) / chunk_length))



where,

Example: R program to divide the vector into chunks with length




# create a vector with 10 elements
vector=c(1,2,3,4,5,6,7,8,9,10)
  
# specify the chunk length as 2
chunklength=2
  
# split the vector by length
print(split(vector,ceiling(seq_along(vector) / chunklength)))

Output:

Example: R program to divide the vector into chunks with length




# create a vector with 10 elements
vector=c(1,2,3,4,5,6,7,8,9,10)
  
# specify the chunk length as 5
chunklength=5
  
# split the vector by length
print(split(vector,ceiling(seq_along(vector) / chunklength)))

Output:

Method 2: By using the number of chunks

In this scenario, the number of chunks is to be provided, so that we can divide the vector using the split() function.

Syntax:

split(vector,  cut(seq_along(vector), chunk_number, labels = FALSE)

where,

Note:

Example: R program to divide the vector into chunks using chunk number




# create a vector with 10 elements
vector=c(1,2,3,4,5,6,7,8,9,10)
  
# specify the chunk number as 5
chunk_no=5
  
# split the vector by chunk number by specifying 
# labels as FALSE
print(split(vector, cut(seq_along(vector),chunk_no,labels = FALSE)))

Output:

Example: R program to divide the vector into chunks using chunk number




# create a vector with 10 elements
vector=c(1,2,3,4,5,6,7,8,9,10)
  
# specify the chunk number as 2
chunkno=2
  
# split the vector by chunk number by 
# unspecifying labels 
print(split(vector, cut(seq_along(vector),chunkno)))

Output:


Article Tags :