Skip to content
AgileLogics
5 min read

Working with Text: stringr

Prerequisites: Strings, dplyr: mutate, summarise, and group_by

stringr gives R a consistent set of string functions: they all start with str_, take the string first (so they work with the pipe), and are vectorized.

library(stringr)

names <- c("  ada lovelace ", "LINUS torvalds", "grace hopper")

str_squish(names)
str_to_title(str_squish(names))
str_length("Hello")
str_detect(names, "hopper")
str_replace_all("2025-01-15", "-", "/")
str_sub("Hello, world", 1, 5)
str_split_1("a,b,c", ",")
str_pad("7", width = 3, pad = "0")
str_c("user", 1:3, sep = "_")
[1] "ada lovelace"   "LINUS torvalds" "grace hopper"
[1] "Ada Lovelace"   "Linus Torvalds" "Grace Hopper"
[1] 5
[1] FALSE FALSE  TRUE
[1] "2025/01/15"
[1] "Hello"
[1] "a" "b" "c"
[1] "007"
[1] "user_1" "user_2" "user_3"
  • str_squish trims the ends and collapses repeated spaces inside.
  • str_detect returns TRUE/FALSE — perfect inside filter().

Extracting with regular expressions

library(stringr)

notes <- c("Order #1042 shipped", "Order #77 pending", "No order")
str_extract(notes, "\\d+")
str_extract(notes, "#(\\d+)", group = 1)
str_detect(notes, "^Order")
[1] "1042" "77"   NA
[1] "1042" "77"   NA
[1]  TRUE  TRUE FALSE
  • str_extract returns one result per input: the first match, or NA when there isn't one.
  • group = 1 returns just the part inside the first parentheses (a capture group) — here, the digits after #.
  • In R strings, a backslash must be doubled: the regex \d+ (one or more digits) is written "\\d+". Test patterns in the Regex Tester first.

In a data pipeline

library(dplyr, warn.conflicts = FALSE)
library(stringr)

tibble(email = c("Ada@Example.com ", "linus@kernel.org")) |>
  mutate(
    email = str_to_lower(str_trim(email)),
    domain = str_extract(email, "(?<=@).+")
  )
# A tibble: 2 × 2
  email            domain
  <chr>            <chr>
1 ada@example.com  example.com
2 linus@kernel.org kernel.org

Common mistakes

  • Single backslashes in patterns: "\d" is an error in R. Write "\\d", or use a raw string: r"(\d+)".