What if you could turn messy stacked data into a neat table with just one simple command?
Why pivot_wider (long to wide) in R Programming? - Purpose & Use Cases
Imagine you have a long list of sales data where each row shows a product, a month, and the sales number. You want to see each product's sales side by side for each month, but the data is all stacked up in one column.
Manually rearranging this data means copying and pasting values into new columns for each month. This is slow, boring, and easy to make mistakes. If the data changes, you have to do it all over again.
The pivot_wider function in R automatically spreads the data from long format into wide format. It creates new columns for each unique value in a chosen column, filling in the matching values. This saves time and avoids errors.
data_wide <- data.frame(product = unique(data$product)) for(month in unique(data$month)) { data_wide[[month]] <- NA for(i in 1:nrow(data)) { if(data$month[i] == month) { data_wide[data_wide$product == data$product[i], month] <- data$sales[i] } } }
library(tidyr) data_wide <- pivot_wider(data, names_from = month, values_from = sales)
You can quickly reshape your data to compare values side by side, making analysis and visualization much easier.
A store manager wants to see monthly sales for each product in columns to spot trends and decide which products to promote.
Manual reshaping is slow and error-prone.
pivot_wider automates turning long data into wide format.
This makes data easier to read and analyze.