01 / 21

pivot_longer() &
pivot_wider()

Master the art of reshaping data in R: convert between wide and long formats using the tidyr package.

R Programming

What is Tidy Data?

The tidyverse in R revolves around a principle: data should be tidy. Tidy data has three rules that make analysis, plotting, and modeling much easier.

1. Columns = Variables
Each column represents one and only one variable.
2. Rows = Observations
Each row represents one and only one observation.
3. Cells = Values
Each cell holds a single value: no lists, no nested data.

Wide vs Long Format

Wide format stores repeated measurements across columns. Long format stacks them into rows with a name-value pair. Neither is "wrong": each suits different tasks.

Wide Format name math science Alice 90 85 Bob 78 92 Carol 95 88 3 rows x 3 cols pivot Long Format name subject score Alice math 90 Alice science 85 Bob math 78 Bob science 92 Carol math 95 Carol science 88 6 rows x 3 cols

Why Reshape Data?

Different tasks demand different shapes. ggplot2 and most tidyverse functions prefer long data, while summary tables and reports often look better wide.

Long is for...
Plotting with ggplot2, group_by() summaries, statistical modeling, and faceting.
Wide is for...
Human-readable tables, reports, correlation matrices, and side-by-side comparison.

The tidyr Package

Both functions live in the tidyr package, part of the tidyverse. They replaced the older gather() and spread() functions with clearer, more consistent syntax.

R
# Load tidyverse (includes tidyr)
library(tidyverse)

# Or load tidyr alone
library(tidyr)
pivot_longer()
Wide → Long: stacks columns into rows.
pivot_wider()
Long → Wide: spreads rows into columns.

pivot_longer() Syntax

R
data %>
  pivot_longer(
    cols      = columns_to_pivot,
    names_to  = "new_name_column",
    values_to = "new_value_column"
  )
1
cols: Which columns to pivot. Use tidy-select helpers like c(math, science) or starts_with("score").
2
names_to: A string: the name of the new column that will hold the old column names.
3
values_to: A string: the name of the new column that will hold the cell values.

pivot_wider() Syntax

R
data %>
  pivot_wider(
    names_from  = name_column,
    values_from = value_column
  )
1
names_from: The column whose unique values become new column headers.
2
values_from: The column whose cell values fill in under those new headers.

pivot_longer vs pivot_wider

pivot_longer() pivot_wider()
Direction Wide → Long Long → Wide
Rows Increase Decrease
Columns Decrease Increase
Key argument cols (which to stack) names_from (which to spread)
Naming args names_to, values_to names_from, values_from
Best for ggplot, modeling Reports, tables

How to Apply Pivoting

1
Identify the goal: Does your task need long or wide data?
2
Spot the ID columns: Which columns should stay put? (e.g., name, id, date)
3
Spot the measurement columns: Which columns hold repeated measures? (e.g., math, science, english)
4
Choose the function: pivot_longer() to stack measurements, pivot_wider() to unstack.
5
Name your new columns: Pick meaningful names like "subject" and "score", not "name" and "value".

Example 1: Wide to Long

We have student test scores stored in wide format. We want to plot all scores by subject using ggplot2.

R
# Starting data: wide format
scores_wide
#   name   math science english
#   Alice    90      85      92
#   Bob      78      92      81

scores_long <- scores_wide %>
  pivot_longer(
    cols      = c(math, science, english),
    names_to  = "subject",
    values_to = "score"
  )

Example 1: Result

Before (Wide) name math sci eng Alice 90 85 92 Bob 78 92 81 pivot_longer() After (Long) name subject score Alice math 90 Alice science 85 Alice english 92 ... + 3 more rows for Bob How values move: Column names → "subject" Cell values → "score" ID cols repeat per row

Example 2: Long to Wide

Now we have a long dataset of quarterly sales. We want each quarter as its own column for a summary report.

R
# Starting data: long format
sales_long
#   product  quarter  revenue
#   Widget   Q1       1200
#   Widget   Q2       1500
#   Gadget   Q1       800
#   Gadget   Q2       950

sales_wide <- sales_long %>
  pivot_wider(
    names_from  = quarter,
    values_from = revenue
  )

Example 3: Tidy-Select Helpers

When you have many columns to pivot, tidy-select helpers save you from listing them all. These work inside the cols argument.

R
# Pivot all columns that start with "score_"
data %>
  pivot_longer(
    cols      = starts_with("score_"),
    names_to  = "test",
    values_to = "result"
  )

# Pivot everything EXCEPT id and name
data %>
  pivot_longer(
    cols      = -c(id, name),
    names_to  = "metric",
    values_to = "value"
  )
starts_with()
Matches column names beginning with a prefix.
ends_with()
Matches column names ending with a suffix.
-c(...)
Selects everything except the listed columns.

They Are Inverses

A key insight: pivot_longer() and pivot_wider() are exact inverses. Applying one after the other returns you to the original data.

Wide fewer rows more columns Long more rows fewer columns pivot_longer() pivot_wider()
R
# Round-trip: data stays identical
data %>
  pivot_longer(...) %>
  pivot_wider(...)
# → back to the original data

Common Mistakes

Forgetting quotes
names_to and values_to need quoted strings: "subject", not bare subject.
Wrong cols selection
Including your ID column in cols will produce nonsensical long data. Only pivot measurement columns.
Duplicate rows in wider
If your data has duplicate name-value combos, pivot_wider() warns about a list-column. Fix duplicates first.

Summary Cheat Sheet

pivot_longer() pivot_wider()
Purpose Stack cols into rows Spread rows into cols
Arg 1 cols (which to pivot) names_from (col for headers)
Arg 2 names_to (string) values_from (col for values)
Arg 3 values_to (string) -
Quoting "quoted" for _to args Bare for _from args
Replaced gather() spread()

Question 1 of 5

Which function converts a wide data frame into a long data frame?

Question 2 of 5

In pivot_longer(), the names_to argument expects:

Question 3 of 5

Which code achieves this?

Question 4 of 5

After applying pivot_longer() to a data frame with 5 rows and 4 measurement columns, how many rows will the result have?

Question 5 of 5

In pivot_wider(), the argument names_from expects: