18.1 stringr package

The stringr package is a simple wrapper around the more complete stringi package. There are a ton of functions (see help(package = "stringr")), but here are some particularly useful ones.

  • str_c() concatenates strings, similar to with paste() and paste0().
str_c("hello", "world", sep = " ")
## [1] "hello world"
  • str_replace(string, pattern, replacment) replaces pattern with replacement.
str_replace("If the future's looking bleek", pattern = fixed("bleek"), replacement = "dark")
## [1] "If the future's looking dark"
  • str_replace_na(string, replacement) replaces NAs.
str_replace_na(c("We're the ones ", NA, "have to shine"), replacement = "who ")
## [1] "We're the ones " "who "            "have to shine"
  • str_split(string, pattern, simplify = FALSE) splits string by pattern into a list of vectors, or matrix if simplify = TRUE.
str_split("If there's no one in control", pattern = " ", simplify = TRUE)
##      [,1] [,2]      [,3] [,4]  [,5] [,6]     
## [1,] "If" "there's" "no" "one" "in" "control"
  • str_c(..., sep) concatenates a vector of strings, separated by sep.
str_c("we're", "the", "ones", "who", "draw", "the", "line", sep = " ")
## [1] "we're the ones who draw the line"

str_sub(string, start, end) returns substring of string from start to end. Use negatives to start from the end of the string.

my_str <- "Although we live in trying times"
str_sub(my_str, start = 1, end = 5)
## [1] "Altho"
str_sub(my_str, start = -4, end = -1)
## [1] "imes"
  • str_length(string) returns the number of characters in a string.
str_length("We're the ones who have to try")
## [1] 30
  • str_detect(string, pattern) returns booleans where string matches pattern.
str_detect(c("Although we know", "that time",  "has wings"), pattern = fixed("wings"))
## [1] FALSE FALSE  TRUE
  • str_match(string, pattern) returns matching strings where string matches pattern.
str_match(c("Although we know", "that time",  "has wings"), pattern = "wings")
##      [,1]   
## [1,] NA     
## [2,] NA     
## [3,] "wings"
  • str_subset(string, pattern) returns string matches where string matches pattern.
str_subset(c("Although we know", "that time",  "has wings"), pattern = fixed("wings"))
## [1] "has wings"
  • str_count(string, pattern) returns a count of matches where string matches pattern.
str_count(c("Although we know", "that time",  "has wings"), pattern = fixed("wings"))
## [1] 0 0 1
  • str_extract(string, pattern) returns the part of the string matching pattern.
str_extract(c("We're the ones", "who have to fly"), pattern = " t..")
## [1] " the" " to "