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:
stringis the text you want to split.patternis the separator or regular expression to split by.nlimits the number of pieces (default is no limit).simplifyifTRUE, 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
| Parameter | Description |
|---|---|
| string | Input text to split |
| pattern | Separator or regex to split by |
| n | Maximum number of pieces (default Inf) |
| simplify | Return 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.