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" |
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 |
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" |
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.