0Pricing
R Academy · Lesson

Long to Wide with pivot_wider()

Spread key-value pairs back into wide format tables.

When to Go Wide

While long format suits analysis, wide format is often needed for reports, spreadsheets, and certain algorithms (e.g., correlation matrices). pivot_wider() is the inverse of pivot_longer() — it spreads values from a column into multiple new columns.

library(tidyr)

# Long format: one row per student-quarter combination
long_df <- data.frame(
  student = c('Alice','Alice','Alice','Bob','Bob','Bob'),
  quarter = c('Q1','Q2','Q3','Q1','Q2','Q3'),
  score = c(85, 88, 92, 90, 85, 88)
)

print(long_df)
cat('\n', nrow(long_df), 'rows x', ncol(long_df), 'cols')

pivot_wider() Basics

pivot_wider(df, names_from, values_from) converts long to wide format. names_from specifies the column whose values become new column names; values_from specifies the column whose values fill those new columns.

library(tidyr)

long_df <- data.frame(
  student = c('Alice','Alice','Alice','Bob','Bob','Bob'),
  quarter = c('Q1','Q2','Q3','Q1','Q2','Q3'),
  score = c(85, 88, 92, 90, 85, 88)
)

wide_df <- pivot_wider(
  long_df,
  names_from = quarter,
  values_from = score
)

print(wide_df)

All lessons in this course

  1. Wide to Long with pivot_longer()
  2. Long to Wide with pivot_wider()
  3. separate() and unite() for String Columns
  4. Nesting and Unnesting Data Frames
← Back to R Academy