R Academy · Lesson

Window Functions: lag, lead, cumsum

Compute running totals, offsets, and cumulative aggregates within groups.

Lesson 2 of 413 steps

Window Functions: lag, lead, cumsum is a free R Academy lesson on CoddyKit. This is lesson 2 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the R Academy learning path, and your progress syncs across the web and the CoddyKit app. The R Academy course includes 4 lessons in total.

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)
  )

lead() — Next Row Value

lead(x, n=1) returns the value from n rows ahead of the current row. The last row(s) will be NA. Useful for computing how the current value compares to future values.

library(dplyr)

df <- data.frame(
  month = 1:5,
  revenue = c(100, 120, 95, 140, 160)
)

df %>%
  mutate(
    next_month = lead(revenue),
    next_2_months = lead(revenue, n = 2),
    will_increase = revenue < lead(revenue)
  )

cumsum() and cumprod()

cumsum(x) computes a running total (cumulative sum). cumprod(x) computes the cumulative product. Both are base-R functions that work seamlessly inside mutate().

library(dplyr)

df <- data.frame(
  month = 1:6,
  revenue = c(100, 120, 95, 140, 160, 130)
)

df %>%
  mutate(
    running_total = cumsum(revenue),
    growth_factor = round(cumprod(1 + (revenue - 100) / 100), 3)
  )

cummax() and cummin()

cummax(x) tracks the running maximum — the highest value seen so far. cummin(x) tracks the running minimum. These are useful for all-time high/low tracking and drawdown analysis.

library(dplyr)

df <- data.frame(
  day = 1:7,
  price = c(50, 52, 48, 55, 53, 58, 56)
)

df %>%
  mutate(
    all_time_high = cummax(price),
    all_time_low = cummin(price),
    drawdown_from_high = price - cummax(price)
  )

row_number() Ranking

row_number() assigns an integer rank to each row. When used after group_by(), it ranks within each group. Ties get consecutive ranks based on their order of appearance.

library(dplyr)

sales <- data.frame(
  region = c('East','East','East','West','West','West'),
  rep = c('Alice','Bob','Carol','Dave','Eve','Frank'),
  revenue = c(200, 150, 180, 120, 190, 160)
)

sales %>%
  group_by(region) %>%
  mutate(rank = row_number(desc(revenue))) %>%
  arrange(region, rank)

ntile() — Bucket into Groups

ntile(x, n) divides the data into n roughly equal-sized buckets and returns the bucket number (1 = lowest). It's useful for creating quartiles, deciles, or percentile groups.

library(dplyr)

df <- data.frame(
  customer = paste0('C', 1:10),
  spend = c(50, 200, 75, 300, 125, 450, 25, 175, 100, 350)
)

df %>%
  mutate(
    quartile = ntile(spend, 4),
    decile = ntile(spend, 10)
  ) %>%
  arrange(spend)

percent_rank() — Relative Standing

percent_rank(x) returns the rank of each value as a proportion between 0 and 1. The minimum gets 0, the maximum gets 1. It tells you where a value falls relative to all others.

library(dplyr)

df <- data.frame(
  student = c('Alice','Bob','Carol','Dave','Eve'),
  score = c(85, 92, 78, 95, 88)
)

df %>%
  mutate(
    pct_rank = round(percent_rank(score), 3),
    top_pct = round(1 - percent_rank(score), 3)
  ) %>%
  arrange(desc(score))

Window Functions in Groups

All window functions become group-aware when combined with group_by(). Each group gets its own independent window — lag/lead don't cross group boundaries, cumsum resets per group, and rankings are within group.

library(dplyr)

df <- data.frame(
  product = c('A','A','A','B','B','B'),
  month = c(1,2,3,1,2,3),
  sales = c(100, 120, 110, 200, 180, 220)
)

df %>%
  group_by(product) %>%
  mutate(
    mom_change = sales - lag(sales),
    cumulative = cumsum(sales),
    rank_in_product = row_number(sales)
  )

Combining Multiple Window Functions

You can chain multiple window functions in one mutate() call to create rich analytical columns. This keeps your pipeline readable and avoids repeated group_by() calls.

library(dplyr)

stock <- data.frame(
  date = as.Date(c('2024-01-01','2024-01-02','2024-01-03',
                   '2024-01-04','2024-01-05')),
  close = c(150.2, 152.8, 149.5, 155.1, 157.3)
)

stock %>%
  mutate(
    prev_close = lag(close),
    daily_return = round((close / lag(close) - 1) * 100, 2),
    running_high = cummax(close),
    distance_from_high = round(close - cummax(close), 2)
  )

lag() with default Argument

lag(x, n=1, default=NA) accepts a default value to fill the initial NA positions. This is useful when you need a numeric baseline instead of missing values in computed columns.

library(dplyr)

df <- data.frame(
  week = 1:5,
  visitors = c(500, 620, 480, 700, 650)
)

df %>%
  mutate(
    prev_week = lag(visitors, default = 0),
    growth = visitors - lag(visitors, default = visitors[1])
  )

Quick Check

What does ntile(x, 4) return for the minimum value in x?

Recap: Window Functions

Key takeaways for window functions in dplyr:

  • lag(x, n) — value n rows before current; lead(x, n) — value n rows ahead
  • cumsum() — running total; cumprod() — running product
  • cummax() / cummin() — running maximum / minimum
  • row_number() — integer rank within group
  • ntile(x, n) — bucket into n groups (1=lowest, n=highest)
  • percent_rank(x) — fractional rank between 0 and 1
  • All window functions are group-aware when combined with group_by()
library(dplyr)

# Comprehensive window function example
data.frame(
  region = c('East','East','East','West','West','West'),
  month = c(1,2,3,1,2,3),
  sales = c(100, 130, 120, 200, 190, 210)
) %>%
  group_by(region) %>%
  mutate(
    mom_chg = sales - lag(sales),
    running_total = cumsum(sales),
    rank = row_number(desc(sales))
  ) %>%
  ungroup()
Free to start

Learn R with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
43
Lessons
159

Frequently Asked Questions

Is the “Window Functions: lag, lead, cumsum” lesson free?

Yes — any 3 lessons of the R Academy learning path, including “Window Functions: lag, lead, cumsum”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The R Academy course includes 4 lessons in total.

What will I learn in “Window Functions: lag, lead, cumsum”?

Compute running totals, offsets, and cumulative aggregates within groups. You practise R Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start R Academy?

No prior experience is required. R Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 2 of 4.

How long does the “Window Functions: lag, lead, cumsum” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this R Academy lesson?

Yes. Every R Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Grouped Summaries and group_by()
  2. Window Functions: lag, lead, cumsum
  3. Multi-table Joins in dplyr
  4. Tidy Evaluation: {{ }} and .data
← Back to R Academy