0
0
R Programmingprogramming~5 mins

pivot_wider (long to wide) in R Programming

Choose your learning style9 modes available
Introduction

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.

You have survey data where each row is a question answer, and you want one row per person with all answers as columns.
You want to turn a list of monthly sales by product into a table with one row per month and columns for each product.
You have measurements taken at different times and want to see all times as columns for each subject.
You want to summarize data so each category becomes a separate column for easier reading.
Syntax
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.

Examples
Turn the 'category' column values into new columns, filling them with 'value' data.
R Programming
pivot_wider(data, names_from = category, values_from = value)
Create columns for each month with sales numbers as values.
R Programming
pivot_wider(data, names_from = month, values_from = sales)
Make columns from 'variable' names and fill with 'measurement' values.
R Programming
pivot_wider(data, names_from = variable, values_from = measurement)
Sample Program

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.

R Programming
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)
OutputSuccess
Important Notes

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.

Summary

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.