typestar

Window functions in R

lag, lead, cumulative functions and ranking, within a group.

library(dplyr)

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

print(mutate(runs,
             previous = lag(tpm),
             change = tpm - lag(tpm),
             running = cumsum(tpm),
             best_so_far = cummax(tpm),
             .by = lang))

print(mutate(runs, rank = dense_rank(desc(tpm)),
             position = row_number(desc(tpm))))

How it works

  1. lag looks back a row; the first value is NA.
  2. cumsum and friends accumulate down the column.
  3. dense_rank and row_number differ on ties.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
332
Tokens
117
Three-star pace
105 tpm

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

Type this snippet

Step 1 of 3 in Windows & rows, step 18 of 27 in dplyr.

← Previous Next →