Pivoting with tidyr in R
Reshaping between wide and long, tidyverse style.
library(tidyr)
library(dplyr)
wide <- tibble(
id = 1:2,
q1 = c(10, 20),
q2 = c(15, 25)
)
long <- wide %>%
pivot_longer(cols = c(q1, q2),
names_to = "quarter",
values_to = "revenue")
back <- long %>%
pivot_wider(names_from = quarter, values_from = revenue)
How it works
pivot_longerstacks columns into key-value pairs.names_toandvalues_toname the new columns.pivot_widerspreads them back out.
Keywords and builtins used here
clibrarypivot_longerpivot_widertibble
The run, in numbers
- Lines
- 16
- Characters to type
- 258
- Tokens
- 75
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 45 seconds.
Step 3 of 3 in Pivoting, step 3 of 12 in Reshaping & reading.