typestar

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

  1. names_from supplies the new column names.
  2. values_fill fills the cells that had no row.
  3. values_fn resolves duplicates instead of making a list column.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Pivoting, step 2 of 12 in Reshaping & reading.

← Previous Next →