R How to Divide a Vector into Groups / Chunks (2 Examples)

In this tutorial you’ll learn how to divide a vector or array into groups in R.

Creation of Example Data

LETTERS              # Print letters to RStudio console
#  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S" "T" "U" "V" "W" "X" "Y" "Z"

Example 1: Sepcify Number of Groups to Split Vector

n_chunk <- 5         # Number of groups
split(LETTERS, cut(seq_along(LETTERS), n_chunk, labels = FALSE))
# $`1`
# [1] "A" "B" "C" "D" "E" "F"
# 
# $`2`
# [1] "G" "H" "I" "J" "K"
# 
# $`3`
# [1] "L" "M" "N" "O" "P"
# 
# $`4`
# [1] "Q" "R" "S" "T" "U"
# 
# $`5`
# [1] "V" "W" "X" "Y" "Z"

Example 2: Sepcify Number of Elements in Each Group to Split Vector

el_chunk <- 5        # Elements in each group
split(LETTERS, ceiling(seq_along(LETTERS) / el_chunk))
# $`1`
# [1] "A" "B" "C" "D" "E"
# 
# $`2`
# [1] "F" "G" "H" "I" "J"
# 
# $`3`
# [1] "K" "L" "M" "N" "O"
# 
# $`4`
# [1] "P" "Q" "R" "S" "T"
# 
# $`5`
# [1] "U" "V" "W" "X" "Y"
# 
# $`6`
# [1] "Z"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top