tidyr
tidyr changes the shape of a table without changing its values. A count matrix arrives wide, with one column per sample, and ggplot2 and most models want it long, with one row per gene and sample. tidyr moves between the two and splits the identifiers that a sample name or a genomic region packs into one string.
Quick reference
Section titled “Quick reference”| Function | Purpose |
|---|---|
pivot_longer() |
Wide to long |
pivot_wider() |
Long to wide |
separate_wider_delim() |
Split a column on a delimiter |
separate_wider_regex() |
Split a column with a regular expression |
separate_longer_delim() |
Split a column into rows |
unite() |
Paste columns into one |
complete() |
Add missing combinations |
nest(), unnest() |
Rows into a list column and back |
unnest_longer() |
List column elements into rows |
fill() |
Copy values into the gaps below or above |
replace_na() |
Replace NA per column |
drop_na() |
Drop rows with NA |
library(tidyr)library(dplyr)
# Match the printed width on this page.options(width = 80)
counts_wide <- tibble( gene = c("TP53", "MYC", "EGFR"), ctrl_1 = c(812L, 1504L, 233L), ctrl_2 = c(945L, 1391L, 260L), trt_1 = c(1720L, 3302L, 118L), trt_2 = c(1688L, 2950L, 141L))counts_wide# A tibble: 3 × 5 gene ctrl_1 ctrl_2 trt_1 trt_2 <chr> <int> <int> <int> <int>1 TP53 812 945 1720 16882 MYC 1504 1391 3302 29503 EGFR 233 260 118 141Wide to long
Section titled “Wide to long”pivot_longer()
Section titled “pivot_longer()”cols names the columns to stack. -gene means every column except gene.
counts_long <- counts_wide |> pivot_longer(cols = -gene, names_to = "sample", values_to = "count")counts_long# A tibble: 12 × 3 gene sample count <chr> <chr> <int> 1 TP53 ctrl_1 812 2 TP53 ctrl_2 945 3 TP53 trt_1 1720 4 TP53 trt_2 1688 5 MYC ctrl_1 1504 6 MYC ctrl_2 1391 7 MYC trt_1 3302 8 MYC trt_2 2950 9 EGFR ctrl_1 23310 EGFR ctrl_2 26011 EGFR trt_1 11812 EGFR trt_2 141Split the names while pivoting
Section titled “Split the names while pivoting”Two names in names_to and a names_sep split ctrl_1 into a condition and a replicate.
Use names_pattern = "(.+)_(\\d+)" when one separator cannot do the split.
counts_wide |> pivot_longer( cols = -gene, names_to = c("condition", "replicate"), names_sep = "_", names_transform = list(replicate = as.integer), values_to = "count" )# A tibble: 12 × 4 gene condition replicate count <chr> <chr> <int> <int> 1 TP53 ctrl 1 812 2 TP53 ctrl 2 945 3 TP53 trt 1 1720 4 TP53 trt 2 1688 5 MYC ctrl 1 1504 6 MYC ctrl 2 1391 7 MYC trt 1 3302 8 MYC trt 2 2950 9 EGFR ctrl 1 23310 EGFR ctrl 2 26011 EGFR trt 1 11812 EGFR trt 2 141Long to wide
Section titled “Long to wide”pivot_wider()
Section titled “pivot_wider()”names_from gives the new column names and values_from fills them.
counts_long |> pivot_wider(names_from = sample, values_from = count)# A tibble: 3 × 5 gene ctrl_1 ctrl_2 trt_1 trt_2 <chr> <int> <int> <int> <int>1 TP53 812 945 1720 16882 MYC 1504 1391 3302 29503 EGFR 233 260 118 141Fill missing cells with values_fill
Section titled “Fill missing cells with values_fill”Some tools write only the nonzero counts. values_fill puts a zero where no row exists, and
names_sort orders the new columns.
sparse_counts <- tribble( ~gene, ~sample, ~count, "TP53", "S1", 12L, "TP53", "S3", 4L, "MYC", "S2", 30L, "CD3E", "S1", 7L)sparse_counts |> pivot_wider( names_from = sample, values_from = count, values_fill = 0L, names_sort = TRUE )# A tibble: 3 × 4 gene S1 S2 S3 <chr> <int> <int> <int>1 TP53 12 0 42 MYC 0 30 03 CD3E 7 0 0Several value columns with names_glue
Section titled “Several value columns with names_glue”A long table of contrasts holds two values per gene and contrast. names_glue builds each
new name, and names_vary = "slowest" keeps the columns of one contrast together.
deg_long <- tribble( ~gene, ~contrast, ~log2fc, ~padj, "TP53", "trt_vs_ctrl", 1.12, 0.003, "TP53", "kd_vs_ctrl", -0.41, 0.52, "MYC", "trt_vs_ctrl", 1.94, 1e-05, "MYC", "kd_vs_ctrl", 0.22, 0.81)deg_long |> pivot_wider( names_from = contrast, values_from = c(log2fc, padj), names_glue = "{contrast}_{.value}", names_vary = "slowest" )# A tibble: 2 × 5 gene trt_vs_ctrl_log2fc trt_vs_ctrl_padj kd_vs_ctrl_log2fc kd_vs_ctrl_padj <chr> <dbl> <dbl> <dbl> <dbl>1 TP53 1.12 0.003 -0.41 0.522 MYC 1.94 0.00001 0.22 0.81Duplicate rows with values_fn
Section titled “Duplicate rows with values_fn”Technical replicates give two values for one cell of the wide table. Without values_fn,
pivot_wider() warns and returns list columns. With values_fn = mean, each cell holds the
mean of its replicates.
qpcr <- tribble( ~gene, ~sample, ~ct, "GAPDH", "S1", 18.2, "GAPDH", "S1", 18.4, "GAPDH", "S2", 18.9, "IL6", "S1", 27.1, "IL6", "S1", 27.5, "IL6", "S2", 24.3)qpcr |> pivot_wider(names_from = sample, values_from = ct, values_fn = mean)# A tibble: 2 × 3 gene S1 S2 <chr> <dbl> <dbl>1 GAPDH 18.3 18.92 IL6 27.3 24.3Split and join columns
Section titled “Split and join columns”separate_wider_delim()
Section titled “separate_wider_delim()”Split a sample name on a delimiter into named columns. A row with too few or too many pieces
stops the call and names the row. too_few and too_many choose another outcome.
runs <- tibble( run = c("SRR1039508_ctrl_rep1", "SRR1039509_trt_rep1", "SRR1039512_ctrl_rep2"))runs |> separate_wider_delim( run, delim = "_", names = c("accession", "condition", "replicate") )# A tibble: 3 × 3 accession condition replicate <chr> <chr> <chr>1 SRR1039508 ctrl rep12 SRR1039509 trt rep13 SRR1039512 ctrl rep2separate_wider_regex()
Section titled “separate_wider_regex()”A region such as chr1:12345-67890 has two delimiters. separate_wider_regex() splits it in
one call. Named patterns become columns and unnamed patterns are dropped.
peaks <- tibble( region = c("chr1:12345-67890", "chr7:100200-300400", "chr17:500600-700800"), score = c(0.95, 0.82, 0.91))peaks |> separate_wider_regex( region, patterns = c(chrom = "chr[^:]+", ":", start = "\\d+", "-", end = "\\d+") ) |> mutate(across(c(start, end), as.integer))# A tibble: 3 × 4 chrom start end score <chr> <int> <int> <dbl>1 chr1 12345 67890 0.952 chr7 100200 300400 0.823 chr17 500600 700800 0.91The separate_wider_*() family supersedes separate() and extract(). Both still work,
and you will meet them in older code.
separate_longer_delim()
Section titled “separate_longer_delim()”separate_longer_delim() gives one row per value instead of one column per value. It suits
a GO annotation that packs several terms into one string, and it supersedes
separate_rows().
The identifiers credit the Gene Ontology Consortium under CC BY 4.0. This example selects five identifiers to demonstrate a table operation.
go_annot <- tibble( gene = c("TP53", "MYC"), go_terms = c("GO:0006915;GO:0006977;GO:0042771", "GO:0008284;GO:0045893"))go_annot |> separate_longer_delim(go_terms, delim = ";")# A tibble: 5 × 2 gene go_terms <chr> <chr>1 TP53 GO:00069152 TP53 GO:00069773 TP53 GO:00427714 MYC GO:00082845 MYC GO:0045893unite()
Section titled “unite()”unite() pastes columns together. remove = FALSE keeps the inputs.
sample_sheet <- tibble( sample = c("S1", "S2", "S3", "S4"), condition = c("ctrl", "ctrl", "trt", "trt"), replicate = c(1, 2, 1, 2))sample_sheet |> unite("label", condition, replicate, sep = "_rep", remove = FALSE)# A tibble: 4 × 4 sample label condition replicate <chr> <chr> <chr> <dbl>1 S1 ctrl_rep1 ctrl 12 S2 ctrl_rep2 ctrl 23 S3 trt_rep1 trt 14 S4 trt_rep2 trt 2Missing combinations
Section titled “Missing combinations”complete()
Section titled “complete()”complete() adds a row for every gene and sample pair that the table lacks. fill sets the
value of the new rows.
sparse_counts |> complete(gene, sample, fill = list(count = 0L))# A tibble: 9 × 3 gene sample count <chr> <chr> <int>1 CD3E S1 72 CD3E S2 03 CD3E S3 04 MYC S1 05 MYC S2 306 MYC S3 07 TP53 S1 128 TP53 S2 09 TP53 S3 4List columns
Section titled “List columns”nest() and unnest()
Section titled “nest() and unnest()”nest(.by = gene) puts each gene’s rows into a small tibble in a data column. The
purrr cheatsheet fits one model per gene from this shape.
nested <- counts_long |> nest(.by = gene)nested# A tibble: 3 × 2 gene data <chr> <list>1 TP53 <tibble [4 × 2]>2 MYC <tibble [4 × 2]>3 EGFR <tibble [4 × 2]>unnest() reverses it.
nested |> unnest(data) |> head(4)# A tibble: 4 × 3 gene sample count <chr> <chr> <int>1 TP53 ctrl_1 8122 TP53 ctrl_2 9453 TP53 trt_1 17204 TP53 trt_2 1688unnest_longer()
Section titled “unnest_longer()”A list column of vectors becomes one row per element.
aliases <- tibble( gene = c("TP53", "BRCA1"), alias = list(c("p53", "LFS1", "BCC7"), c("BRCC1", "FANCS", "RNF53")))aliases |> unnest_longer(alias)# A tibble: 6 × 2 gene alias <chr> <chr>1 TP53 p532 TP53 LFS13 TP53 BCC74 BRCA1 BRCC15 BRCA1 FANCS6 BRCA1 RNF53Missing values
Section titled “Missing values”A QC table from a spreadsheet often has the batch only on the first row of each batch, and an empty adapter cell where the trimming report found no adapter.
qc <- tribble( ~sample, ~batch, ~rin, ~adapter_pct, "S1", "B1", 9.1, 0.4, "S2", NA, 8.7, NA, "S3", NA, NA, 1.2, "S4", "B2", 7.9, NA, "S5", NA, 8.2, 0.3)fill()
Section titled “fill()”fill() copies the last value down into the gaps. tidyr 1.3.2 adds .by to fill within
groups.
qc |> fill(batch, .direction = "down")# A tibble: 5 × 4 sample batch rin adapter_pct <chr> <chr> <dbl> <dbl>1 S1 B1 9.1 0.42 S2 B1 8.7 NA3 S3 B1 NA 1.24 S4 B2 7.9 NA5 S5 B2 8.2 0.3replace_na()
Section titled “replace_na()”replace_na() takes a named list, one replacement per column.
qc |> replace_na(list(adapter_pct = 0))# A tibble: 5 × 4 sample batch rin adapter_pct <chr> <chr> <dbl> <dbl>1 S1 B1 9.1 0.42 S2 <NA> 8.7 03 S3 <NA> NA 1.24 S4 B2 7.9 05 S5 <NA> 8.2 0.3drop_na()
Section titled “drop_na()”With no columns named, drop_na() drops a row with a missing value in any column. Name a
column to check only that one.
qc |> drop_na(rin)# A tibble: 4 × 4 sample batch rin adapter_pct <chr> <chr> <dbl> <dbl>1 S1 B1 9.1 0.42 S2 <NA> 8.7 NA3 S4 B2 7.9 NA4 S5 <NA> 8.2 0.3See also
Section titled “See also”- Reshaping explains when a table should be wide or long and shows the same pivots in Polars.
- Missing Values covers how to detect, drop, fill,
and impute
NAbefore an analysis. - Tidyverse Essentials explains why plotting
and model functions expect the long format that
pivot_longer()returns. - The dplyr cheatsheet covers the joins and summaries that usually follow a pivot.
Scientific references
Section titled “Scientific references”The tidyr package by Wickham, Vaughan, and Girlich supplies the functions that tidy messy data.
Further reading
Section titled “Further reading”-
The guide covers compound column names, repeated measurements, list columns and aggregation when a wide cell has multiple values.