R How to Divide Character String into Pieces (Example Code)

This page explains how to cut a character string into multiple pieces in R.

Creation of Example Data

x <- paste(letters, collapse = "")                 # Character string in R
x                                                  # Display character string in RStudio
# [1] "abcdefghijklmnopqrstuvwxyz"

Example: Apply strsplit Function to Chop Character String into Even Sized Groups

n <- 3                                             # Specifying number of characters per chunk
strsplit(gsub(paste0("([[:alnum:]]{", n, "})"),    # Applying strsplit function
              "\1 ", x), " ")[[1]]
# [1] "abc" "def" "ghi" "jkl" "mno" "pqr" "stu" "vwx" "yz"

Further Resources & Related Tutorials

Please find some related R programming tutorials below.

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