pivot_longer in R
Wide columns become rows: the shape most tidyverse functions want.
library(tidyr)
library(dplyr)
wide <- tibble(
lang = c("r", "python"),
week_1 = c(88, 104),
week_2 = c(96, 99),
week_3 = c(92, 101)
)
long <- pivot_longer(wide,
cols = starts_with("week"),
names_to = "week",
names_prefix = "week_",
names_transform = list(week = as.integer),
values_to = "tpm")
print(long)
print(summarise(long, mean_tpm = mean(tpm), .by = lang))
How it works
colsselects the columns to melt.names_toandvalues_toname the two new columns.names_prefixandnames_transformclean the names as they arrive.
Keywords and builtins used here
clibrarylistmeanpivot_longerprintstarts_withsummarisetibble
The run, in numbers
- Lines
- 18
- Characters to type
- 364
- Tokens
- 110
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 66 seconds.
Step 1 of 3 in Pivoting, step 1 of 12 in Reshaping & reading.