library(tidyverse) # includes stringrstringr at a Glance
The str_* functions, before we learn regex
What is stringr?
stringr is the tidyverse package for working with text (strings). Almost all of its functions:
- start with
str_, so typingstr_in Positron and pressing Tab lists them all; - take the string (or vector of strings) as their first argument, so they work with the pipe
|>; - are vectorized: give them a vector of 100 strings and they return 100 answers.
Many of them also take a pattern argument: the text to look for. Today the patterns are plain text, like "an". In the regex lesson, we’ll replace plain text with regular expressions: patterns that can describe things like “any digit” or “a word that starts with a capital letter”. The functions stay the same; only the pattern gets more powerful.
The table
Every example in the table is real R code, and every result was computed when this page was rendered. Results are shown the way the R console prints them: [1] marks the first element of the output. The pattern? column marks the functions that take a pattern; those are the ones regex will power up.
| Category | Function | What it does | Pattern? | Example | Result |
|---|---|---|---|---|---|
| Combine | str_c() |
glue strings together | str_c("data", "309", sep = "-") |
[1] "data-309" |
|
| Combine | str_flatten() |
collapse a vector into one string | str_flatten(c("a", "b", "c"), ", ") |
[1] "a, b, c" |
|
| Combine | str_glue() |
fill {variables} into a template | str_glue("{name} is {age}", name = "Ana", age = 20) |
[1] "Ana is 20" |
|
| Length | str_length() |
count the characters | str_length(c("pear", "banana")) |
[1] 4 6 |
|
| Case | str_to_lower() |
lowercase | str_to_lower("Data Science") |
[1] "data science" |
|
| Case | str_to_upper() |
UPPERCASE | str_to_upper("Data Science") |
[1] "DATA SCIENCE" |
|
| Case | str_to_title() |
Capitalize Each Word | str_to_title("data science is fun") |
[1] "Data Science Is Fun" |
|
| Case | str_to_sentence() |
Capitalize the first word only | str_to_sentence("data science is fun") |
[1] "Data science is fun" |
|
| Whitespace | str_trim() |
remove spaces at the start and end | str_trim(" hello ") |
[1] "hello" |
|
| Whitespace | str_squish() |
trim, and shrink inner runs of spaces to one | str_squish(" too many spaces ") |
[1] "too many spaces" |
|
| Whitespace | str_pad() |
pad to a fixed width | str_pad("7", width = 3, pad = "0") |
[1] "007" |
|
| Pieces | str_sub() |
the characters from position start to end | str_sub("Marquette", 1, 4) |
[1] "Marq" |
|
| Pieces | str_trunc() |
shorten long strings, adding … | str_trunc("Northern Michigan University", 12) |
[1] "Northern ..." |
|
| Pieces | str_dup() |
repeat a string | str_dup("ha", 3) |
[1] "hahaha" |
|
| Detect | str_detect() |
TRUE/FALSE: does it contain the pattern? | ✓ | str_detect(c("apple", "banana", "pear"), "an") |
[1] FALSE TRUE FALSE |
| Detect | str_starts() |
TRUE/FALSE: does it start with the pattern? | ✓ | str_starts(c("apple", "banana", "pear"), "b") |
[1] FALSE TRUE FALSE |
| Detect | str_ends() |
TRUE/FALSE: does it end with the pattern? | ✓ | str_ends(c("apple", "banana", "pear"), "r") |
[1] FALSE FALSE TRUE |
| Detect | str_count() |
how many times the pattern appears | ✓ | str_count(c("apple", "banana", "pear"), "a") |
[1] 1 3 1 |
| Detect | str_which() |
positions of the strings that match | ✓ | str_which(c("apple", "banana", "pear"), "e") |
[1] 1 3 |
| Detect | str_subset() |
keep only the strings that match | ✓ | str_subset(c("apple", "banana", "pear"), "p") |
[1] "apple" "pear" |
| Detect | str_locate() |
start and end position of the first match | ✓ | str_locate("banana", "an") |
start 2, end 3 |
| Replace | str_replace() |
replace the first match | ✓ | str_replace("banana", "a", "o") |
[1] "bonana" |
| Replace | str_replace_all() |
replace every match | ✓ | str_replace_all("banana", "a", "o") |
[1] "bonono" |
| Replace | str_remove() |
delete the first match | ✓ | str_remove("banana", "a") |
[1] "bnana" |
| Replace | str_remove_all() |
delete every match | ✓ | str_remove_all("banana", "a") |
[1] "bnn" |
| Extract | str_extract() |
the first matching text (NA if none) | ✓ | str_extract(c("apple", "kiwi"), "pp") |
[1] "pp" NA |
| Extract | str_extract_all() |
every matching text, as a list | ✓ | str_extract_all("banana", "an") |
[1] "an" "an" |
| Split | str_split() |
split at the pattern, as a list | ✓ | str_split("a,b,c", ",") |
[1] "a" "b" "c" |
| Split | str_split_i() |
split, and keep piece number i | ✓ | str_split_i("Doe, Jane", ", ", 2) |
[1] "Jane" |
| Sort | str_sort() |
sort alphabetically | str_sort(c("pear", "apple", "banana")) |
[1] "apple" "banana" "pear" |
|
| View | str_view() |
show the matches, highlighted with < > | ✓ | str_view("banana", "an") |
b<an><an>a |
Notes on the table
Vectors in, vectors out
Most str_ functions return one answer per input string: str_detect() on three fruits gives three TRUE/FALSE values. Two kinds of functions break that pattern:
str_subset()andstr_which()return only the strings (or positions) that match, so the answer can be shorter than the input.str_extract_all()andstr_split()can find several pieces in one string, so they return a list: one vector of pieces per input string. The table shows the pieces for the first string.
str_detect() inside filter()
str_detect() returns TRUE/FALSE, which is exactly what filter() needs. This is the most common way you’ll use stringr with data:
tibble(fruit = fruit) |>
filter(str_detect(fruit, "berry"))# A tibble: 14 × 1
fruit
<chr>
1 bilberry
2 blackberry
3 blueberry
4 boysenberry
5 cloudberry
6 cranberry
7 elderberry
8 goji berry
9 gooseberry
10 huckleberry
11 mulberry
12 raspberry
13 salal berry
14 strawberry
str_*() inside mutate()
The other functions slot into mutate() to clean or create columns:
tibble(name = c(" ana LOPEZ", "ben smith ")) |>
mutate(
clean = name |> str_squish() |> str_to_title(),
last = str_split_i(clean, " ", 2),
length = str_length(clean)
)# A tibble: 2 × 4
name clean last length
<chr> <chr> <chr> <int>
1 " ana LOPEZ" Ana Lopez Lopez 9
2 "ben smith " Ben Smith Smith 9
First match vs. every match
Several functions come in pairs: the plain version handles the first match, and the _all version handles every match.
| first match | every match |
|---|---|
str_replace() |
str_replace_all() |
str_remove() |
str_remove_all() |
str_extract() |
str_extract_all() |
Looking ahead to regex
So far every pattern was literal text. Next we’ll write patterns like these, and every ✓ function in the table will accept them:
| pattern | matches |
|---|---|
"^b" |
a b at the start of the string |
"r$" |
an r at the end of the string |
"[aeiou]" |
any one vowel |
"\\d" |
any digit |
"a+" |
one or more as in a row |
For example, str_count(fruit, "[aeiou]") counts the vowels in every fruit name.
More
?str_detect(or any function name) opens its help page with examples.- The stringr cheat sheet fits all of this on two pages.
- R for Data Science, Ch. 14 (Strings) and Ch. 15 (Regular expressions).