0
0
R Programmingprogramming~5 mins

pivot_longer (wide to long) in R Programming

Choose your learning style9 modes available
Introduction

pivot_longer helps you turn wide tables into long tables, making data easier to analyze and visualize.

You have a table with many columns representing similar data points and want to stack them into rows.
You want to prepare data for plotting where each row is one observation.
You need to simplify a dataset with repeated column patterns into a tidy format.
You want to convert survey results from multiple columns into a single column with values.
You want to reshape data to use functions that expect long format input.
Syntax
R Programming
pivot_longer(data, cols, names_to = "name", values_to = "value")

data is your original wide data frame.

cols specifies which columns to turn from wide to long.

Examples
This turns the columns Jan, Feb, Mar into two columns: month and sales.
R Programming
pivot_longer(df, cols = c("Jan", "Feb", "Mar"), names_to = "month", values_to = "sales")
This selects all columns starting with 'Q' and pivots them longer.
R Programming
pivot_longer(df, cols = starts_with("Q"), names_to = "quarter", values_to = "revenue")
Sample Program

This example converts monthly sales columns into a long format with one row per month per id.

R Programming
library(tidyr)
df <- data.frame(
  id = 1:2,
  Jan = c(10, 20),
  Feb = c(15, 25),
  Mar = c(20, 30)
)
long_df <- pivot_longer(df, cols = c("Jan", "Feb", "Mar"), names_to = "month", values_to = "sales")
print(long_df)
OutputSuccess
Important Notes

pivot_longer keeps columns not specified in cols as they are.

You can use helpers like starts_with() or matches() to select columns.

Use names_to and values_to to name the new columns clearly.

Summary

pivot_longer changes wide data into long data by stacking columns into rows.

It makes data tidy and easier to work with for analysis and plotting.

Use cols to pick columns to pivot, and name new columns with names_to and values_to.