str_split() splits each string element into multiple pieces based on the specified separator, and returns a list.
library(stringr) fruits <-c("mango, peach, kiwi, and lemon", "apple, banana, and orange") # split strings at the site of commasstr_split(fruits, pattern =",")
Output:
[[1]] [1] "mango" " peach" " kiwi" " and lemon" [[2]] [1] "apple" " banana" " and orange"
The argument n specifies the maximum number of pieces each string element should be split into. In the example below, we limit the maximum number of pieces each string element is split into to be 3.
str_split(fruits, pattern =",", n =3)
Output:
[[1]] [1] "mango" " peach" " kiwi, and lemon" [[2]] [1] "apple" " banana" " and orange"
Use simplify = T to return the split strings as a matrix.
str_split(fruits, pattern =",", n =3, simplify = T)
Output:
[,1] [,2] [,3] [1,] "mango" " peach" " kiwi, and lemon" [2,] "apple" " banana" " and orange"
When returned as a matrix, if the specified n value (e.g., n = 5) exceeds the maximal number of possible splits, empty columns will be created to make a total of n columns.
str_split(fruits, pattern =",", n =5, simplify = T)