pivot_wider helps you change data from a long list format to a wider table format. This makes it easier to compare values side by side.
pivot_wider (long to wide) in R Programming
pivot_wider(data, names_from = column_to_use_as_new_columns, values_from = column_with_values)
data is your original long data frame.
names_from decides which column's values become new column names.
values_from decides which column's values fill the new columns.
pivot_wider(data, names_from = category, values_from = value)
pivot_wider(data, names_from = month, values_from = sales)
pivot_wider(data, names_from = variable, values_from = measurement)
This example starts with a long data frame where each person (id) has height and weight in separate rows. Using pivot_wider, we create one row per person with height and weight as separate columns.
library(tidyr) # Example long data frame long_data <- data.frame( id = c(1, 1, 2, 2), key = c("height", "weight", "height", "weight"), value = c(170, 65, 180, 75) ) # Use pivot_wider to make wide data wide_data <- pivot_wider(long_data, names_from = key, values_from = value) print(wide_data)
If there are multiple values for the same id and name, pivot_wider will give an error unless you specify how to handle duplicates.
You can use the values_fill argument to fill missing values with something like 0 or NA.
pivot_wider changes data from long to wide format.
It creates new columns from one column's values and fills them with another column's data.
This helps make data easier to read and compare side by side.