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.
Practice
(1/5)
1. What does the pivot_longer() function do in R's tidyverse?
easy
A. It filters rows based on a condition.
B. It creates new columns by splitting existing ones.
C. It transforms wide data into long data by stacking columns into rows.
D. It sorts data by a specific column.
Solution
Step 1: Understand the purpose of pivot_longer()
The function is designed to reshape data from wide format (many columns) to long format (fewer columns, more rows).
Step 2: Identify the correct description
Among the options, only It transforms wide data into long data by stacking columns into rows. correctly describes stacking columns into rows, which is what pivot_longer does.
Final Answer:
It transforms wide data into long data by stacking columns into rows. -> Option C
Quick Check:
pivot_longer = wide to long [OK]
Hint: pivot_longer stacks columns into rows to tidy data [OK]
Common Mistakes:
Confusing pivot_longer with filtering or sorting functions
Thinking it splits columns instead of stacking
Assuming it creates new columns instead of reshaping
2. Which of the following is the correct syntax to pivot columns Jan and Feb into longer format with new columns named Month and Sales?
You want to pivot it longer so that the quarter and year are separate columns named Quarter and Year, and the values go into Score. Which code achieves this?