Skip to content

stringr

Every stringr function starts with str_ and takes the strings first and the pattern second. Most return a vector the same length as the input, so they drop into mutate() and filter() as they are. Patterns are ICU regular expressions unless you wrap them in fixed(). The examples clean versioned Ensembl IDs, BioMart descriptions, sample names, and genomic regions.

Function Purpose
str_detect() TRUE where the pattern matches
str_starts() TRUE where the string starts with the pattern
str_ends() TRUE where the string ends with the pattern
str_subset() The strings that match
str_count() Number of matches per string
str_extract() First match, or one capture group
str_extract_all() All matches, as a list
str_match() Capture groups as a matrix
str_remove(), str_replace_all() Delete or replace matches
str_split(), str_split_i() Split into a list, or take one piece
str_c(), str_flatten() Paste element by element, or collapse
str_glue() Fill a template from variables
str_sub() Characters by position
str_pad() Pad to a fixed width
str_wrap() Break text into lines of a maximum width
str_squish(), str_trim() Clean whitespace
str_to_upper(), str_to_snake() Change case
str_sort(numeric = TRUE) Natural sort

The gene names and HGNC accessions credit the HUGO Gene Nomenclature Committee, which releases its data under CC0. The selected descriptions use the Ensembl annotation format; the original EGFR response confirms that source field.

library(stringr)
library(dplyr)
# Match the printed width on this page.
options(width = 80)
genes <- tibble(
ensembl = c(
"ENSG00000141510.18", "ENSG00000012048.23", "ENSG00000146648.21",
"ENSG00000136997.21", "ENSG00000010610.10", "ENSG00000153563.16",
"ENSG00000120217.14", "ENSG00000049768.16"
),
symbol = c("TP53", "BRCA1", "EGFR", "MYC", "CD4", "CD8A", "CD274", "FOXP3"),
description = c(
"tumor protein p53 [Source:HGNC Symbol;Acc:HGNC:11998]",
"BRCA1 DNA repair associated [Source:HGNC Symbol;Acc:HGNC:1100]",
"epidermal growth factor receptor [Source:HGNC Symbol;Acc:HGNC:3236]",
"MYC proto-oncogene [Source:HGNC Symbol;Acc:HGNC:7553]",
"CD4 molecule [Source:HGNC Symbol;Acc:HGNC:1678]",
"CD8 subunit alpha [Source:HGNC Symbol;Acc:HGNC:1706]",
"CD274 molecule [Source:HGNC Symbol;Acc:HGNC:17635]",
"forkhead box P3 [Source:HGNC Symbol;Acc:HGNC:6106]"
)
)
genes
# A tibble: 8 × 3
ensembl symbol description
<chr> <chr> <chr>
1 ENSG00000141510.18 TP53 tumor protein p53 [Source:HGNC Symbol;Acc:HGNC:1199…
2 ENSG00000012048.23 BRCA1 BRCA1 DNA repair associated [Source:HGNC Symbol;Acc…
3 ENSG00000146648.21 EGFR epidermal growth factor receptor [Source:HGNC Symbo…
4 ENSG00000136997.21 MYC MYC proto-oncogene [Source:HGNC Symbol;Acc:HGNC:755…
5 ENSG00000010610.10 CD4 CD4 molecule [Source:HGNC Symbol;Acc:HGNC:1678]
6 ENSG00000153563.16 CD8A CD8 subunit alpha [Source:HGNC Symbol;Acc:HGNC:1706]
7 ENSG00000120217.14 CD274 CD274 molecule [Source:HGNC Symbol;Acc:HGNC:17635]
8 ENSG00000049768.16 FOXP3 forkhead box P3 [Source:HGNC Symbol;Acc:HGNC:6106]

str_detect() returns TRUE or FALSE per string, which is what filter() needs. negate = TRUE flips the result.

genes |>
filter(str_detect(symbol, "^CD")) |>
pull(symbol)
[1] "CD4" "CD8A" "CD274"

Wrap the pattern in regex(ignore_case = TRUE).

str_detect(genes$description, regex("dna repair", ignore_case = TRUE))
[1] FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE

str_starts() tests only the start of each string. Here it keeps the human Ensembl gene IDs from a mixed list that also holds a mouse gene, an Entrez ID, and a transcript.

ids <- c("ENSG00000141510", "ENSMUSG00000059552", "7157", "ENST00000269305")
str_starts(ids, "ENSG")
[1] TRUE FALSE FALSE FALSE

str_ends() tests only the end. The pattern is a regular expression, so wrap a file extension in fixed() to keep its dots literal.

files <- c("S1_R1.fastq.gz", "S1_R2.fastq.gz", "S1.bam", "S1.bam.bai")
str_ends(files, fixed(".fastq.gz"))
[1] TRUE TRUE FALSE FALSE

str_subset() returns the matching strings themselves, here the symbols that end in a digit.

str_subset(genes$symbol, "\\d$")
[1] "TP53" "BRCA1" "CD4" "CD274" "FOXP3"

str_count() counts matches per string, so GC content is two calls. Since stringr 1.6, the names of the input carry through to the result.

probes <- c(p1 = "ATGCGCGTTA", p2 = "AATTTATAAA", p3 = "GGCGCCGCGG")
str_count(probes, "[GC]") / str_length(probes)
p1 p2 p3
0.5 0.0 1.0

str_extract() returns the first match, or NA when there is none.

str_extract(genes$description, "HGNC:\\d+")
[1] "HGNC:11998" "HGNC:1100" "HGNC:3236" "HGNC:7553" "HGNC:1678"
[6] "HGNC:1706" "HGNC:17635" "HGNC:6106"

group = 1 returns the text inside the first pair of parentheses rather than the whole match. Here it keeps the gene name and drops the BioMart source tag.

str_extract(genes$description, "^(.+) \\[Source", group = 1)
[1] "tumor protein p53" "BRCA1 DNA repair associated"
[3] "epidermal growth factor receptor" "MYC proto-oncogene"
[5] "CD4 molecule" "CD8 subunit alpha"
[7] "CD274 molecule" "forkhead box P3"

str_extract_all() returns every match, as a list with one element per input string.

The terminology examples credit the Gene Ontology Consortium under CC BY 4.0. The lesson selects or shortens labels for demonstration. This credit also applies to the later str_wrap() example.

go_text <- c(
"GO:0006915 apoptotic process; GO:0006977 DNA damage response",
"GO:0008284 positive regulation of cell population proliferation"
)
str_extract_all(go_text, "GO:\\d{7}")
[[1]]
[1] "GO:0006915" "GO:0006977"
[[2]]
[1] "GO:0008284"

str_match() returns a matrix with the whole match in the first column and one column per group. Named groups name the columns.

regions <- c("chr17:7661779-7687538", "chr7:55019017-55211628")
str_match(regions, "(?<chrom>chr[^:]+):(?<start>\\d+)-(?<end>\\d+)")
chrom start end
[1,] "chr17:7661779-7687538" "chr17" "7661779" "7687538"
[2,] "chr7:55019017-55211628" "chr7" "55019017" "55211628"

For a data frame column, tidyr::separate_wider_regex() does the same split into columns. The tidyr cheatsheet shows it on peak regions.

A versioned ID such as ENSG00000141510.18 will not join to an unversioned one. Remove the dot and the digits at the end.

str_remove(genes$ensembl, "\\.\\d+$")
[1] "ENSG00000141510" "ENSG00000012048" "ENSG00000146648" "ENSG00000136997"
[5] "ENSG00000010610" "ENSG00000153563" "ENSG00000120217" "ENSG00000049768"

In a regular expression . matches any character, so the first call replaces every character. fixed(".") matches only the dot.

sample_names <- c("tumor.rep1.R1", "normal.rep2.R1")
str_replace_all(sample_names, ".", "_")
str_replace_all(sample_names, fixed("."), "_")
[1] "_____________" "______________"
[1] "tumor_rep1_R1" "normal_rep2_R1"

A named vector maps each pattern to its replacement. str_replace() changes only the first match in each string, and str_replace_all() changes all of them.

str_replace_all(
c("ctrl_1", "ctrl_2", "trt_1"),
c("ctrl" = "control", "trt" = "treated")
)
[1] "control_1" "control_2" "treated_1"

str_split() returns a list, because each string can split into a different number of pieces.

fastqs <- c("SRR1039508_1.fastq.gz", "SRR1039509_2.fastq.gz")
str_split(fastqs, fixed("_"))
[[1]]
[1] "SRR1039508" "1.fastq.gz"
[[2]]
[1] "SRR1039509" "2.fastq.gz"

str_split_i() returns the piece at one position as a plain vector. A negative position counts from the end.

str_split_i(fastqs, fixed("_"), 1)
[1] "SRR1039508" "SRR1039509"

str_c() pastes element by element. str_flatten() collapses a vector into one string.

str_c("S", 1:3, "_", c("ctrl", "ctrl", "trt"))
str_flatten(genes$symbol[1:4], collapse = ", ")
[1] "S1_ctrl" "S2_ctrl" "S3_trt"
[1] "TP53, BRCA1, EGFR, MYC"

str_glue() evaluates the code inside {}, so a label can format a number as it builds.

de <- tibble(symbol = c("TP53", "MYC"), padj = c(3.1e-08, 0.0042))
de |>
mutate(label = str_glue("{symbol} (padj {signif(padj, 2)})")) |>
pull(label)
TP53 (padj 3.1e-08)
MYC (padj 0.0042)

str_sub() takes start and end positions, and a negative position counts from the end. The pbmc3k barcodes end in -1, which end = -3 removes.

The selected barcodes credit 10x Genomics, 3k PBMCs from a Healthy Donor, May 26, 2016, under CC BY 4.0. The example removes the barcode suffix.

barcodes <- c("AAACATACAACCAC-1", "AAACATTGAGCTAC-1", "AAACATTGATCAGC-1")
str_sub(barcodes, end = -3)
[1] "AAACATACAACCAC" "AAACATTGAGCTAC" "AAACATTGATCAGC"

Zero padding makes sample IDs sort in numeric order as text.

str_c("S", str_pad(c(1, 12, 103), width = 3, pad = "0"))
[1] "S001" "S012" "S103"

str_wrap() breaks text at spaces so that no line is longer than width. A long GO term then fits on a plot axis, through scale_y_discrete(labels = \(x) str_wrap(x, width = 25)).

go_term <- "positive regulation of transcription by RNA polymerase II"
cat(str_wrap(go_term, width = 25), sep = "\n")
positive regulation of
transcription by RNA
polymerase II

str_trim() removes spaces at the ends. str_squish() also collapses repeated spaces and tabs inside the string.

str_squish(" tp53 \t ")
str_to_upper(c("tp53", "brca1"))
[1] "tp53"
[1] "TP53" "BRCA1"

stringr 1.6 adds str_to_snake(), str_to_camel(), and str_to_kebab(). The first turns spreadsheet headers into column names that need no backticks. It also splits a digit from the letters before it, so Log2 becomes log_2.

str_to_snake(c("Sample ID", "Log2 Fold Change", "RIN score"))
[1] "sample_id" "log_2_fold_change" "rin_score"

Text sorting puts chr10 before chr2. numeric = TRUE sorts the digits as numbers.

chroms <- c("chr10", "chr2", "chrX", "chr1", "chr22")
str_sort(chroms)
str_sort(chroms, numeric = TRUE)
[1] "chr1" "chr10" "chr2" "chr22" "chrX"
[1] "chr1" "chr2" "chr10" "chr22" "chrX"

In an R string a backslash is written twice, so the regex \d is "\\d" in code.

Pattern Matches
. Any single character
\\d, \\w, \\s A digit, a word character, a whitespace character
[GC], [^:] One character in the set, one character not in the set
*, +, ? Zero or more, one or more, zero or one
{7}, {2,4} Exactly 7, from 2 to 4
^, $ Start of the string, end of the string
(...) A capture group
(?<name>...) A named capture group
a|b a or b
fixed(".") A literal string, no regex
  • String Ops shows the same operations side by side in stringr and the Polars .str namespace, ending with messy sample names.
  • Gene ID Mapping maps symbols, Entrez IDs, and Ensembl IDs once the strings are clean.
  • The forcats cheatsheet uses str_sort() to put chromosomes in order on a plot axis.

The stringr package by Wickham supplies consistent wrappers for common string operations.

  • stringr regular expressions

    The guide explains escaping, anchors, capture groups and vectorized matches for the identifier operations used here.