typestar

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

  1. pivot_longer stacks columns into key-value pairs.
  2. names_to and values_to name the new columns.
  3. pivot_wider spreads them back out.

Keywords and builtins used here

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.

Type this snippet

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

← Previous Next →