Window Functions: lag, lead, cumsum
Compute running totals, offsets, and cumulative aggregates within groups.
What Are Window Functions?
Window functions compute values relative to the current row without collapsing the data. Unlike summarize(), they keep all rows. In dplyr, window functions are used inside mutate() — often after group_by().
library(dplyr)
# Monthly revenue — we want to compare each month to previous
df <- data.frame(
month = 1:6,
revenue = c(100, 120, 95, 140, 160, 130)
)
print(df)lag() — Previous Row Value
lag(x, n=1) returns the value from n rows before the current row. The first row(s) will be NA. It's ideal for computing period-over-period changes.
library(dplyr)
df <- data.frame(
month = 1:6,
revenue = c(100, 120, 95, 140, 160, 130)
)
df %>%
mutate(
prev_revenue = lag(revenue),
change = revenue - lag(revenue),
pct_change = round(100 * (revenue - lag(revenue)) / lag(revenue), 1)
)All lessons in this course
- Grouped Summaries and group_by()
- Window Functions: lag, lead, cumsum
- Multi-table Joins in dplyr
- Tidy Evaluation: {{ }} and .data