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 withpaste()
andpaste0()
.
## [1] "hello world"
str_replace(string, pattern, replacment)
replacespattern
withreplacement
.
## [1] "If the future's looking dark"
str_replace_na(string, replacement)
replaces NAs.
## [1] "We're the ones " "who " "have to shine"
str_split(string, pattern, simplify = FALSE)
splitsstring
bypattern
into a list of vectors, or matrix ifsimplify = TRUE
.
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] "If" "there's" "no" "one" "in" "control"
str_c(..., sep)
concatenates a vector of strings, separated bysep
.
## [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.
## [1] "Altho"
## [1] "imes"
str_length(string)
returns the number of characters in a string.
## [1] 30
str_detect(string, pattern)
returns booleans wherestring
matchespattern
.
## [1] FALSE FALSE TRUE
str_match(string, pattern)
returns matching strings wherestring
matchespattern
.
## [,1]
## [1,] NA
## [2,] NA
## [3,] "wings"
str_subset(string, pattern)
returns string matches wherestring
matchespattern
.
## [1] "has wings"
str_count(string, pattern)
returns a count of matches wherestring
matchespattern
.
## [1] 0 0 1
str_extract(string, pattern)
returns the part of thestring
matchingpattern
.
## [1] " the" " to "