0
0
R-programmingHow-ToBeginner · 3 min read

How to Use str_split in R: Simple String Splitting Guide

In R, use str_split() from the stringr package to split a string into pieces based on a pattern. It returns a list where each element contains the split parts of the input string.
📐

Syntax

The basic syntax of str_split() is:

  • str_split(string, pattern, n = Inf, simplify = FALSE)

Here:

  • string is the text you want to split.
  • pattern is the separator or regular expression to split by.
  • n limits the number of pieces (default is no limit).
  • simplify if TRUE, returns a character matrix instead of a list.
r
str_split(string, pattern, n = Inf, simplify = FALSE)
💻

Example

This example shows how to split a sentence into words using space as the separator.

r
library(stringr)
text <- "Learn R programming easily"
split_text <- str_split(text, " ")
print(split_text)
Output
[[1]] [1] "Learn" "R" "programming" "easily"
⚠️

Common Pitfalls

One common mistake is forgetting to load the stringr package before using str_split(). Another is expecting a vector output instead of a list, which can cause confusion when accessing results.

Also, using the wrong pattern can lead to unexpected splits.

r
## Wrong: Not loading stringr
# split_text <- str_split("a,b,c", ",") # Error: could not find function "str_split"

## Right: Load stringr first
library(stringr)
split_text <- str_split("a,b,c", ",")
print(split_text)

## Access first element to get vector
print(split_text[[1]])
Output
[[1]] [1] "a" "b" "c" [1] "a" "b" "c"
📊

Quick Reference

ParameterDescription
stringInput text to split
patternSeparator or regex to split by
nMaximum number of pieces (default Inf)
simplifyReturn character matrix if TRUE, else list

Key Takeaways

Use str_split() from stringr to split strings by a pattern in R.
Always load the stringr package before using str_split().
str_split() returns a list; access elements with [[1]] to get vectors.
Use the simplify parameter to get a matrix output if needed.
Check your pattern carefully to split strings as expected.