Skip to main content
v2026.11,858 entries · CC-BY 4.0

stringr Cheat Sheet: Core Functions for Text Cleaning in R

stringr cheat sheet: R string functions grouped by task, mapped to base R, with a worked example cleaning sample IDs and notes on NA and output.

Written and maintained by CASRAI Editorial Board

Last updated

Short answer. stringr is an R package, part of the tidyverse, that wraps string handling in consistently named functions that all start with str_ and all take the string as their first argument. This cheat sheet groups its functions by the task you are doing (detect, extract, replace, split, join, trim, change case, sort), maps each to its base R equivalent, and walks through a worked example of cleaning sample-ID text. It is written for researchers and analysts who clean text columns in R. stringr is an R package only; it has no official Python port.

Facts about the package were read on 2026-11-08 from the CRAN package page (stringr 1.6.0, published 2025-11-04, requires R 4.1.0 or later, MIT licence), the tidyverse reference index and the “From base R” vignette. The official one-page sheet is Posit’s String manipulation with stringr (CC BY-SA), listed under Sources.

What stringr is used for in research

Research datasets routinely carry free-text columns: sample or participant IDs typed by hand, affiliation strings, free-text survey answers, file names, and reference lists. stringr covers the repetitive operations on these: finding which rows contain a pattern, pulling a piece out, replacing or removing text, splitting one column into several, and standardising whitespace and case. It is built on the stringi package, which CRAN lists as one of its imports.

If you only need one operation, CASRAI already has single-function guides: substr in R, concatenate in R, lower case in R and uppercase in R. This page is the package-level map.

Install or access

stringr is distributed on CRAN, and it is also installed as part of the tidyverse bundle.

install.packages("stringr")   # or install.packages("tidyverse")
library(stringr)

CRAN states that stringr 1.6.0 needs R 4.1.0 or later. Its listed imports are cli, glue, lifecycle, magrittr, rlang, stringi and vctrs; install.packages() fetches these for you. Documentation lives at stringr.tidyverse.org, with four vignettes on CRAN: Introduction to stringr, From base R, Regular expressions, and Locale sensitive functions.

The cheat sheet: functions by task

The groups below follow the tidyverse reference index. The “Task” column is a plain-language description of what each function family does.

Group Functions Task
Detect and count matches str_detect, str_count, str_starts, str_ends, str_like, str_ilike Test whether, or how often, a pattern occurs. str_like and str_ilike use SQL-style LIKE and ILIKE matching.
Locate and extract str_extract, str_extract_all, str_match, str_match_all, str_locate, str_locate_all Return the matched text, its capture groups or its position.
Subset a vector str_subset, str_which Keep the elements that match, or return their indices.
Replace and remove str_replace, str_replace_all, str_remove, str_remove_all, str_replace_na Substitute or delete matched text.
Split str_split, str_split_1, str_split_fixed, str_split_i Break strings into pieces on a pattern.
Join str_c, str_flatten, str_flatten_comma, str_glue, str_glue_data Combine strings, collapse a vector into one string, or interpolate values into a template.
Characters and length str_length, str_width, str_sub, str_sub_all, str_dup, str_pad, str_trunc, str_wrap Measure, slice, repeat, pad, truncate or wrap strings.
Whitespace str_trim, str_squish str_trim removes whitespace at the start and/or end only; str_squish also collapses repeated internal whitespace.
Case str_to_upper, str_to_lower, str_to_title, str_to_sentence, str_to_camel, str_to_snake, str_to_kebab Change case; the locale-aware variants accept a locale argument.
Order and compare str_sort, str_order, str_rank, str_equal, str_unique Locale-aware sorting, ranking and comparison.
Pattern modifiers regex(), fixed(), coll(), boundary(), str_escape Change how a pattern is interpreted (regular expression, literal text, collation rules, text boundaries) or escape special characters.
Helpers and data str_view, word, invert_match, str_conv; datasets sentences, fruit, words Preview matches, pick words, convert encodings, and practise on built-in data.

stringr and base R equivalents

The “From base R” vignette maps each stringr function to the base function it replaces. It also states the main difference: in base R the pattern usually comes first, while in stringr the string to manipulate always comes first, which is what makes stringr calls work cleanly in pipes.

stringr Base R
str_detect() grepl()
str_which() grep()
str_subset() grep(value = TRUE)
str_locate() regexpr()
str_extract() regmatches() with regexpr()
str_replace() / str_replace_all() sub() / gsub()
str_length() nchar()
str_sub() substr()
str_to_lower() tolower()
str_trim() trimws()
str_flatten() paste(collapse = )
str_dup() strrep()
str_split() strsplit()
str_wrap() strwrap()
str_sort() sort()

Step-by-step: cleaning sample IDs

Illustrative example. The data below are invented for demonstration and do not come from any real study. The task: standardise hand-typed sample IDs, flag the ones from one site, and pull out the numeric part.

  1. Load the package and create the data.
    library(stringr)
    ids <- c("  site-A_017 ", "SITE-b_102", "site-A_5", "control")
  2. Trim and collapse whitespace. str_squish() removes leading and trailing whitespace and collapses internal runs to a single space.
    ids <- str_squish(ids)

    The first element becomes "site-A_017".

  3. Standardise case.
    ids <- str_to_lower(ids) # "site-a_017" "site-b_102" "site-a_5" "control"
  4. Detect rows from one site. str_detect() returns one TRUE or FALSE per element.
    str_detect(ids, "^site-a") # TRUE FALSE TRUE FALSE

    The ^ anchors the match to the start of the string.

  5. Extract the number. str_extract() returns the first match and NA for strings with no match, so the result is always the same length as the input.
    str_extract(ids, "\\d+") # "017" "102" "5" NA
  6. Replace a separator. str_replace_all() replaces every match; str_replace() replaces only the first.
    str_replace_all(ids, "[-_]", " ") # "site a 017" "site b 102" "site a 5" "control"
  7. Use it inside a data frame. Because the string is the first argument, the calls compose with mutate() in dplyr:
    library(dplyr)
    df <- tibble(id = ids) |>
      mutate(number = as.integer(str_extract(id, "\\d+")))

    The number column is 17, 102, 5, NA. Regular-expression syntax beyond this is covered in the Regular expressions vignette and in the “Regular Expressions” section of the Posit sheet.

Output and how to read it

  • Vectors in, vectors out. str_detect(), str_extract() and str_replace_all() return a vector the same length as the input, so they can be added directly as data-frame columns. The reference page for str_extract() states that its result has the same length as string.
  • NA means “no match” for extractors. In the vignette’s example, str_extract(shopping_list, "\\d+") on c("apples x4", "bag of flour", "10", "milk x2") returns "4" NA "10" "2".
  • The _all variants return lists. str_extract_all() returns a list of character vectors, with character(0) for elements that do not match. Setting simplify = TRUE returns a character matrix instead. Base regmatches(), by contrast, drops strings with no match, according to the vignette.
  • str_locate() returns a matrix of start and end positions, with NA in both columns for a non-match.
  • str_sub() differs from substr(). Negative positions count from the end, and the first argument is recycled to the length of start and end, whereas base substr() silently uses only the first value. Replacement also differs: str_sub(x, 1, 3) <- "x" turns "ABCDEF" into "xDEF", while base substr(x, 1, 3) <- "x" gives "xBCDEF".

Troubleshooting

My pattern matches nothing, or matches the wrong thing

By default, pattern is treated as a regular expression (per the str_extract() reference). If you are searching for literal text containing characters such as . or (, wrap it in fixed() or pass it through str_escape(). str_view() lets you preview what a pattern matches before you apply it.

Backslashes behave strangely

In R string literals a backslash must itself be escaped, so the regular expression d is written "\d", as in the examples above.

I passed arguments in the base R order

In stringr the string always comes first, so write str_detect(fruit, "a"), not the pattern-first order that grepl() uses.

Sorting or case conversion differs by language

The locale-aware functions (str_sort(), str_to_upper() and others) take a locale argument. The vignette shows str_to_upper("i", locale = "tr") returning the Turkish capital dotted I. The Locale sensitive functions vignette covers this in detail.

Installation fails

Check your R version against the requirement above (R 4.1.0 or later for stringr 1.6.0), then update R.

Free alternatives

Option What it is Where it fits
Base R string functions Built into R: grepl, sub, gsub, substr, strsplit, trimws, nchar (see the mapping table above) No extra package needed; pattern-first argument order.
stringi The package stringr imports (listed on CRAN) Direct access to the underlying text-processing functions.
glue Another CRAN import of stringr; stringr’s str_glue() is its string-interpolation function Building strings from templates.

stringr is released under the MIT licence per CRAN.

FAQ

Is there an official stringr cheat sheet?

Yes. Posit publishes String manipulation with stringr, covering stringr 1.6.0 and last updated August 2026 per its page, under a CC BY-SA licence. Its sections are Detect Matches, Mutate Strings, Subset Strings, Join and Split, Manage Lengths, Order Strings, Helpers and Regular Expressions.

Does stringr work in Python?

No. stringr is an R package published on CRAN; this page does not cover any Python equivalent.

What is the difference between str_trim() and str_squish()?

str_trim() removes whitespace only at the start and/or end of a string. str_squish() does that and also reduces repeated whitespace inside the string to a single space.

What is the difference between str_replace() and str_replace_all()?

str_replace() replaces only the first match in each string; str_replace_all() replaces every match.

Why does str_extract() return NA?

It returns NA for each string where the pattern does not match, which keeps the output the same length as the input.

Which version of R does stringr need?

CRAN lists R 4.1.0 or later for stringr 1.6.0 (checked 2026-11-08).

Sources

Related on CASRAI: reading Excel files in R with readxl and cleaning data in Excel.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about stringr Cheat Sheet: Core Functions for Text Cleaning in R

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →