pivot_wider in R
The inverse: one row per id, one column per key.
library(tidyr)
library(dplyr)
long <- tibble(
lang = c("r", "r", "python", "python", "python"),
day = c("mon", "tue", "mon", "tue", "tue"),
tpm = c(88, 96, 104, 99, 101)
)
print(pivot_wider(long, names_from = day, values_from = tpm,
values_fn = mean, values_fill = 0))
print(pivot_wider(long, names_from = day, values_from = tpm,
names_prefix = "tpm_", values_fn = max))
How it works
names_fromsupplies the new column names.values_fillfills the cells that had no row.values_fnresolves duplicates instead of making a list column.
Keywords and builtins used here
clibrarypivot_widerprinttibble
The run, in numbers
- Lines
- 14
- Characters to type
- 373
- Tokens
- 114
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 68 seconds.
Step 2 of 3 in Pivoting, step 2 of 12 in Reshaping & reading.