Wide to Long with pivot_longer()
Reshape wide format tables into tidy long format for analysis.
Wide vs Long Data Formats
Data can be stored in wide format (one row per subject, multiple value columns) or long format (one row per observation, a column for variable name and another for value). Many R packages for visualization and modeling expect long format.
library(tidyr)
library(dplyr)
# Wide format: each quarter is a column
wide_df <- data.frame(
student = c('Alice','Bob','Carol'),
q1 = c(85, 90, 78),
q2 = c(88, 85, 80),
q3 = c(92, 88, 84)
)
print(wide_df)
cat('\nShape:', nrow(wide_df), 'rows x', ncol(wide_df), 'cols')pivot_longer() Basics
pivot_longer(df, cols, names_to, values_to) converts wide format to long format. cols specifies which columns to pivot, names_to is the new column for the old column names, and values_to is the new column for the values.
library(tidyr)
wide_df <- data.frame(
student = c('Alice','Bob','Carol'),
q1 = c(85, 90, 78),
q2 = c(88, 85, 80),
q3 = c(92, 88, 84)
)
long_df <- pivot_longer(
wide_df,
cols = c(q1, q2, q3),
names_to = 'quarter',
values_to = 'score'
)
print(long_df)All lessons in this course
- Wide to Long with pivot_longer()
- Long to Wide with pivot_wider()
- separate() and unite() for String Columns
- Nesting and Unnesting Data Frames