A catalog. Open it when you forget which str_ function to call.
Where you are. This is a catalog, not the next lesson. Open it when you forget which str_ function to call. The lessons continue with note 9.5.
stringr (part of the tidyverse) gives consistent, readable functions for string work. The main functions start with str_, take the string first and the pattern second, and are vectorized. Patterns are regex (via the stringi/ICU engine) unless wrapped in a helper.
library(stringr)
1. Detect and count
Function
What it does
Example
str_detect(x, p)
TRUE/FALSE: does the pattern occur?
str_detect("apple", "pp") → TRUE
str_count(x, p)
Number of matches
str_count("banana", "a") → 3
str_starts(x, p)
Starts with pattern?
str_starts("apple", "a") → TRUE
str_ends(x, p)
Ends with pattern?
str_ends("apple", "e") → TRUE
str_which(x, p)
Indices of elements that match
str_which(c("a","b","ab"), "a") → 1 3
str_equal(x, y)
Compare strings (Unicode-aware)
2. Extract and locate
Function
What it does
Example
str_extract(x, p)
First match in each string
str_extract("ab12cd34", "\\d+") → "12"
str_extract_all(x, p)
All matches (returns a list)
→ "12" "34"
str_match(x, p)
First match plus capture groups (matrix)
str_match("2026-10", "(\\d+)-(\\d+)")
str_match_all(x, p)
Same, for all matches
str_locate(x, p)
Start and end position of first match
str_locate_all(x, p)
Positions of all matches
str_subset(x, p)
Return only the elements that match
str_subset(c("cat","dog"), "c") → "cat"
3. Replace and remove
Function
What it does
Example
str_replace(x, p, r)
Replace first match
str_replace("aaa", "a", "b") → "baa"
str_replace_all(x, p, r)
Replace all matches
→ "bbb"
str_remove(x, p)
Delete first match
str_remove_all(x, p)
Delete all matches
str_replace_na(x, r)
Replace NA with a string
Backreferences in replacements use \\1: str_replace("John Smith", "(\\w+) (\\w+)", "\\2, \\1") → "Smith, John". You can also pass a named vector for several replacements at once: str_replace_all(x, c("a" = "1", "b" = "2")).
4. Length and subsetting
Function
What it does
Example
str_length(x)
Number of characters
str_length("hello") → 5
str_sub(x, start, end)
Extract by position (negatives count from the end). One character is str_sub(x, i, i)