typestar

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

  1. cols selects the columns to melt.
  2. names_to and values_to name the two new columns.
  3. names_prefix and names_transform clean the names as they arrive.

Keywords and builtins used here

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.

Type this snippet

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

Next →