Skip to content

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.

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 1688
2 MYC 1504 1391 3302 2950
3 EGFR 233 260 118 141

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 233
10 EGFR ctrl_2 260
11 EGFR trt_1 118
12 EGFR trt_2 141

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 233
10 EGFR ctrl 2 260
11 EGFR trt 1 118
12 EGFR trt 2 141

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 1688
2 MYC 1504 1391 3302 2950
3 EGFR 233 260 118 141

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 4
2 MYC 0 30 0
3 CD3E 7 0 0

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.52
2 MYC 1.94 0.00001 0.22 0.81

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.9
2 IL6 27.3 24.3

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 rep1
2 SRR1039509 trt rep1
3 SRR1039512 ctrl rep2

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.95
2 chr7 100200 300400 0.82
3 chr17 500600 700800 0.91

The separate_wider_*() family supersedes separate() and extract(). Both still work, and you will meet them in older code.

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:0006915
2 TP53 GO:0006977
3 TP53 GO:0042771
4 MYC GO:0008284
5 MYC GO:0045893

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 1
2 S2 ctrl_rep2 ctrl 2
3 S3 trt_rep1 trt 1
4 S4 trt_rep2 trt 2

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 7
2 CD3E S2 0
3 CD3E S3 0
4 MYC S1 0
5 MYC S2 30
6 MYC S3 0
7 TP53 S1 12
8 TP53 S2 0
9 TP53 S3 4

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 812
2 TP53 ctrl_2 945
3 TP53 trt_1 1720
4 TP53 trt_2 1688

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 p53
2 TP53 LFS1
3 TP53 BCC7
4 BRCA1 BRCC1
5 BRCA1 FANCS
6 BRCA1 RNF53

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() 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.4
2 S2 B1 8.7 NA
3 S3 B1 NA 1.2
4 S4 B2 7.9 NA
5 S5 B2 8.2 0.3

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.4
2 S2 <NA> 8.7 0
3 S3 <NA> NA 1.2
4 S4 B2 7.9 0
5 S5 <NA> 8.2 0.3

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.4
2 S2 <NA> 8.7 NA
3 S4 B2 7.9 NA
4 S5 <NA> 8.2 0.3
  • 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 NA before 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.

The tidyr package by Wickham, Vaughan, and Girlich supplies the functions that tidy messy data.

  • tidyr pivot guide

    The guide covers compound column names, repeated measurements, list columns and aggregation when a wide cell has multiple values.