pivot_longer() &
pivot_wider()
Master the art of reshaping data in R: convert between wide and long formats using the tidyr package.
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.
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.
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.
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.
# Load tidyverse (includes tidyr) library(tidyverse) # Or load tidyr alone library(tidyr)
pivot_longer() Syntax
data %> pivot_longer( cols = columns_to_pivot, names_to = "new_name_column", values_to = "new_value_column" )
pivot_wider() Syntax
data %> pivot_wider( names_from = name_column, values_from = value_column )
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
Example 1: Wide to Long
We have student test scores stored in wide format. We want to plot all scores by subject using ggplot2.
# 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
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.
# 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.
# 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" )
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.
# Round-trip: data stays identical data %> pivot_longer(...) %> pivot_wider(...) # → back to the original data
Common Mistakes
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
A data frame df has columns: student, quiz_1, quiz_2, quiz_3. You want to create a long data frame with columns student, quiz, and grade.
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: