R tidyr
last modified November 19, 2026
Most data arrives in a shape that is convenient for a spreadsheet and
inconvenient for analysis. Values that should be one column are spread across
several, two variables are packed into one cell, or every row mixes an
identifier with a measurement. Tidy data fixes one rule: every
variable is a column, every observation is a row, and every cell holds one
value. The tidyr package provides the verbs that move a table between shapes
without manual loops. This article covers pivot_longer,
pivot_wider, separate, unite, and the
functions that handle missing values in a table. The examples use tidyr 1.3.2
and dplyr 1.2.1 with R 4.5.2.
The examples need the tidyr and dplyr packages, which are not part of base R.
Install them once with install.packages(c("tidyr", "dplyr")); the
installing packages section of the
introduction explains the details.
From wide to long
The pivot_longer function gathers several columns into two: one
column holds the old column names, called the key, and one holds the
values. The cols argument selects the columns to gather, and the
result is usually longer and narrower than the input.
library(tidyr)
wide <- tibble(
name = c("Ada", "Grace"),
math = c(90, 85),
art = c(80, 95)
)
print(wide)
print(pivot_longer(wide, cols = c(math, art),
names_to = "subject", values_to = "score"))
The wide table stores two subjects as two columns, which makes it hard to
compute one average per subject. The long table has one row per student and
subject pair, so subject is now a variable with the values
math and art. The order follows the input columns:
both of Ada's scores come before Grace's.
$ Rscript longer.R # A tibble: 2 × 3 name math art <chr> <dbl> <dbl> 1 Ada 90 80 2 Grace 85 95 # A tibble: 4 × 3 name subject score <chr> <chr> <dbl> 1 Ada math 90 2 Ada art 80 3 Grace math 85 4 Grace art 95
Names, prefixes, and types
Column names often carry a prefix that repeats, such as a unit or a year. The
argument names_prefix removes that prefix from the gathered
names, and names_to gives the key column a meaningful name. The
key column is character by default, even when the names look like numbers.
library(tidyr)
wide <- tibble(
name = c("Ada", "Grace"),
score_2025 = c(90, 85),
score_2026 = c(92, 88)
)
print(pivot_longer(wide, cols = starts_with("score_"),
names_to = "year", values_to = "score",
names_prefix = "score_"))
The selector starts_with("score_") picks both score columns
without naming them one by one. Removing the prefix leaves the years 2025 and
2026, and the values move into score. If the year should be
numeric, convert it afterwards with mutate(year = as.integer(year));
tidyr keeps the key as text because not every key is a number.
$ Rscript longer-options.R # A tibble: 4 × 3 name year score <chr> <chr> <dbl> 1 Ada 2025 90 2 Ada 2026 92 3 Grace 2025 85 4 Grace 2026 88
From long to wide
pivot_wider is the reverse operation. It takes the values of one
column as the new column names and the values of another column as the cells.
The remaining columns identify the rows, and every unique combination of the
key and the identifier must be unique.
library(tidyr)
long <- tibble(
name = c("Ada", "Ada", "Grace", "Grace"),
subject = c("math", "art", "math", "art"),
score = c(90, 80, 85, 95)
)
print(pivot_wider(long, names_from = subject, values_from = score))
The four long rows become two wide rows with a column per subject. The
name column identifies the rows because it was not named in
names_from or values_from. If a student had two
scores in the same subject, the pivot would produce a list column, because
two values cannot occupy one cell.
$ Rscript wider.R # A tibble: 2 × 3 name math art <chr> <dbl> <dbl> 1 Ada 90 80 2 Grace 85 95
Filling missing cells
A combination that does not appear in the long table becomes a missing cell in
the wide table. The argument values_fill supplies a replacement
for those cells, which is useful when the absence really means zero, such as
no score recorded for a subject that was not taken.
library(tidyr)
long <- tibble(
name = c("Ada", "Ada", "Grace"),
subject = c("math", "art", "math"),
score = c(90, 80, 85)
)
print(pivot_wider(long, names_from = subject, values_from = score,
values_fill = 0))
Grace has no art score, so her art cell would be NA without the
argument; with values_fill = 0 it becomes zero. Zero is the right
replacement only when it means "none"; for a missing measurement the cell
should stay missing, because a zero would distort every average that follows.
$ Rscript wider-options.R # A tibble: 2 × 3 name math art <chr> <dbl> <dbl> 1 Ada 90 80 2 Grace 85 0
Splitting a column
separate splits one column into several at a fixed separator.
The into argument names the new columns, and sep
describes the split point. The argument convert = TRUE turns
numeric-looking pieces into numbers, which is almost always wanted for dates
and counts.
library(tidyr)
people <- tibble(
name = c("Ada Lovelace", "Grace Hopper"),
born = c("1815-12-10", "1906-12-09")
)
print(separate(people, name, into = c("first", "last"), sep = " "))
print(separate(people, born, into = c("year", "month", "day"),
sep = "-", convert = TRUE))
The full name becomes a first and a last name at the space. The date becomes
three integer columns because convert = TRUE was given; without
it, all three would be character. The separator is treated as a regular
expression, so a pattern such as "[-/]" can split on either a
hyphen or a slash.
$ Rscript split-column.R # A tibble: 2 × 3 first last born <chr> <chr> <chr> 1 Ada Lovelace 1815-12-10 2 Grace Hopper 1906-12-09 # A tibble: 2 × 4 name year month day <chr> <int> <int> <int> 1 Ada Lovelace 1815 12 10 2 Grace Hopper 1906 12 9
Joining two columns
unite is the opposite of separate: it joins several
columns into one with a separator. The new column takes the name given as the
second argument, and the source columns are removed unless
remove = FALSE is set.
library(tidyr)
parts <- tibble(
first = c("Ada", "Grace"),
last = c("Lovelace", "Hopper")
)
print(unite(parts, name, first, last, sep = " "))
print(unite(parts, name, first, last, sep = " ", remove = FALSE))
The first call produces a single name column and drops the two
source columns. The second keeps them, which is useful when the parts are
still needed for sorting or matching. Missing values in any part become the
text "NA" by default; the argument na.rm = TRUE
leaves them out instead.
$ Rscript join-columns.R # A tibble: 2 × 1 name <chr> 1 Ada Lovelace 2 Grace Hopper # A tibble: 2 × 3 name first last <chr> <chr> <chr> 1 Ada Lovelace Ada Lovelace 2 Grace Hopper Grace Hopper
Missing values in a table
tidyr provides three focused tools for gaps. drop_na removes rows
that contain a missing value, replace_na fills selected columns
with a chosen value, and fill carries the last observed value
down a column. They complement the base functions from the missing values
article rather than replace them.
library(tidyr)
scores <- tibble(
name = c("Ada", "Grace", "Alan"),
math = c(90, NA, 66),
art = c(80, 95, NA)
)
print(drop_na(scores))
print(replace_na(scores, list(math = 0, art = 0)))
print(fill(tibble(x = c(1, NA, NA, 4)), x))
drop_na keeps only Ada, because both other rows have a gap.
replace_na fills the two numeric columns with zero through a
named list, so a zero in math does not affect art.
fill replaces the two missing values with the preceding one,
which is the usual way to carry a recorded value forward in a log.
$ Rscript table-missing.R
# A tibble: 1 × 3
name math art
<chr> <dbl> <dbl>
1 Ada 90 80
# A tibble: 3 × 3
name math art
<chr> <dbl> <dbl>
1 Ada 90 80
2 Grace 0 95
3 Alan 66 0
# A tibble: 4 × 1
x
<dbl>
1 1
2 1
3 1
4 4
A complete example
The next script reshapes a wide score table into long form and computes the average per subject. It uses tidyr for the pivot and dplyr for the grouped summary, which is the usual division of labour: tidyr changes the shape, and dplyr computes on the result.
library(tidyr)
suppressPackageStartupMessages(library(dplyr))
wide <- tibble(
name = c("Ada", "Grace", "Alan"),
math = c(90, 85, 66),
art = c(80, 95, 70)
)
long <- pivot_longer(wide, cols = c(math, art),
names_to = "subject", values_to = "score")
print(long)
print(long |> group_by(subject) |> summarise(avg = mean(score)))
The long table has six rows, one for each student and subject. The grouped
summary then returns one row per subject: art averages 81.67 and mathematics
80.33. The same numbers could be computed from the wide table with
rowMeans and a transpose, but the long form extends to any number
of subjects without changing the code.
$ Rscript report.R # A tibble: 6 × 3 name subject score <chr> <chr> <dbl> 1 Ada math 90 2 Ada art 80 3 Grace math 85 4 Grace art 95 5 Alan math 66 6 Alan art 70 # A tibble: 2 × 2 subject avg <chr> <dbl> 1 art 81.7 2 math 80.3
Next steps
The dplyr article explains the grouped summary
used in the final example. The tibbles article
covers the table type that both packages use, and the
missing values article explains the base
R behaviour behind NA. The
data frames article shows the wide shape that
most files arrive in.
Source
In this article we have gathered columns with pivot_longer and
spread them again with pivot_wider. We removed name prefixes,
filled missing combinations, split a column with separate, and
joined columns with unite. We handled gaps with
drop_na, replace_na, and fill, and
finished with a wide-to-long-to-summary pipeline. The series continues with
R data.table.
Author
List all R Language tutorials.