Splitting strings

String Manipulation with stringr in R

Charlotte Wickham

Assistant Professor at Oregon State University

str_split()

"Tom & Jerry"

String Manipulation with stringr in R

str_split()

"Tom & Jerry"

str_split(string = "Tom & Jerry", pattern = " & ")
[[1]]
"Tom"   "Jerry"
str_split("Alvin & Simon & Theodore", pattern = " & ")
[[1]]
"Alvin"    "Simon"    "Theodore"
str_split("Alvin & Simon & Theodore", pattern = " & ", n = 2)
[[1]]
"Alvin"            "Simon & Theodore"
String Manipulation with stringr in R

str_split() returns a list

chars <- c("Tom & Jerry", 
           "Alvin & Simon & Theodore")

str_split(chars, pattern = " & ")
[[1]]
"Tom" "Jerry"
[[2]]
"Alvin" "Simon" "Theodore"
String Manipulation with stringr in R

str_split() can return a matrix

chars <- c("Tom & Jerry", 
           "Alvin & Simon & Theodore")

str_split(chars, pattern = " & ", simplify = TRUE)
     [,1]    [,2]    [,3]      
[1,] "Tom"   "Jerry" ""        
[2,] "Alvin" "Simon" "Theodore"
String Manipulation with stringr in R

Combing with lapply()

chars <- c("Tom & Jerry", 
           "Alvin & Simon & Theodore")

split_chars <- str_split(chars, pattern = " & ")
split_chars
[[1]]
"Tom"   "Jerry"
[[2]]
"Alvin"    "Simon"    "Theodore"
lapply(split_chars, length)
[[1]]
2
[[2]]
3
String Manipulation with stringr in R

Let's practice!

String Manipulation with stringr in R

Preparing Video For Download...