typestar

Nesting in R

A list column of data frames, one per group — the tidy way to model per group.

library(tidyr)
library(dplyr)
library(purrr)

runs <- tibble(
  lang = c("r", "r", "r", "python", "python", "python"),
  day = c(1, 2, 3, 1, 2, 3),
  tpm = c(88, 92, 96, 99, 104, 101)
)

nested <- nest(runs, data = c(day, tpm))
print(nested)

fitted <- mutate(nested,
                 rows = map_int(data, nrow),
                 slope = map_dbl(data, ~ coef(lm(tpm ~ day, data = .x))[[2]]))
print(select(fitted, lang, rows, slope))
print(unnest(nested, data) |> nrow())

How it works

  1. nest(.by = ) puts each group's rows in a data column.
  2. map over that column fits or summarizes per group.
  3. unnest flattens it back out.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
430
Tokens
158
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 1 of 3 in Nesting & gaps, step 6 of 12 in Reshaping & reading.

← Previous Next →

Nesting in other languages