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
laglooks back a row; the first value is NA.cumsumand friends accumulate down the column.dense_rankandrow_numberdiffer on ties.
Keywords and builtins used here
ccummaxcumsumdense_rankdesclaglibrarymutateprintrow_numbertibble
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.
Step 1 of 3 in Windows & rows, step 18 of 27 in dplyr.