dplyr Tutorial

Clean, transform and summarise data with dplyr

Practical lessons on filter, mutate, group_by, joins and more — with sample data and exercises.

dplyr cheat sheet Get help with your data

Window Functions in R with dplyr: A Practical Guide

Updated

Learn how window functions in R calculate values across related rows without collapsing your dataset. This beginner-friendly dplyr guide explains lag(), lead(), ranking, cumulative totals, grouped calculations, and practical examples for business analytics and time-series data.

What are window functions in R?

Window functions in R calculate a value for each row by using information from other rows. They are especially useful when you need to compare an observation with the previous observation, identify its rank, calculate a running total, or compare a row with a group-level statistic.

In a typical dplyr workflow, a window function is used inside mutate() so the new result appears alongside the original columns. For example, a sales dataset can keep each month's revenue and add the previous month's revenue and the change between the two.

library(dplyr)

sales |>
  arrange(date) |>
  mutate(previous_sales = lag(sales))

The main benefit is that the rows are not collapsed into a single summary. The function adds information to each observation, which makes window functions useful for data cleaning, reporting, forecasting features, performance analysis, and exploratory data analysis.

Remember: window functions rely on the order of the data for sequence-based calculations. Use arrange() to establish the correct order before using lag(), lead(), or cumulative functions. If calculations should restart for each customer, region, product, or other group, combine them with group_by().

Common window functions in dplyr

FunctionPurposeTypical example
lag()Return a previous valueCompare this month's sales with last month's sales
lead()Return a subsequent valueCompare today's value with the next observation
row_number()Assign a unique row position or rankIdentify the first, second, and third records
min_rank()Rank values while leaving gaps after tiesRank students by score
dense_rank()Rank values without gaps after tiesRank products by revenue
cumsum()Calculate a cumulative sumTrack revenue accumulated over time
cummin() / cummax()Track the minimum or maximum observed so farTrack a running high or low
cume_dist() / percent_rank()Calculate relative rank measuresUnderstand where a score sits within a group

Create example data for window functions in R

We will use monthly sales for three salespeople. Each person has observations over time, allowing us to calculate previous sales, next sales, changes, rankings, and cumulative totals.

library(dplyr)

monthly_sales <- tibble(
  salesperson = c("Amina", "Amina", "Amina",
                  "Bilal", "Bilal", "Bilal",
                  "Sara", "Sara"),
  region = c("North", "North", "North",
             "South", "South", "South",
             "North", "North"),
  date = as.Date(c(
    "2026-01-01", "2026-02-01", "2026-03-01",
    "2026-01-01", "2026-02-01", "2026-03-01",
    "2026-01-01", "2026-02-01"
  )),
  sales = c(1200, 1450, 1380, 900, 1050, 1250, 1600, 1550)
)

monthly_sales
Example monthly sales data
salespersonregiondatesales

The data is arranged by salesperson in the example table, but the rows are not necessarily ordered by date across the entire dataset. Before doing a time-based calculation, we will explicitly sort the data by salesperson and date.

1. Use lag() in R to compare previous values

The dplyr-compatible lag() function returns the value from an earlier position in a vector. By default, lag(sales) shifts the vector by one row, so each row receives the previous row's sales value. The first row has no previous observation, so its lagged value is NA.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(previous_sales = lag(sales)) |>
  ungroup()

Grouping by salesperson is important here: Amina's previous value should be Amina's earlier month, not the last value recorded for another salesperson. The arrange(salesperson, date) step makes the sequence explicit.

Change the number of positions with n

The n argument controls how far to shift. For monthly data, lag(sales, n = 2) retrieves the value from two observations earlier.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(sales_two_periods_ago = lag(sales, n = 2)) |>
  ungroup()

This is useful when comparing a value with two weeks ago, two transactions earlier, or the corresponding position in a sequence. It does not automatically identify the same calendar date in a dataset with missing or irregular dates; it shifts by row position.

Set a default value

You can provide a default for positions that have no earlier value. The default should be compatible with the vector's type.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(previous_sales = lag(sales, default = 0)) |>
  ungroup()

Use a default of zero only when it makes sense for the analysis. A missing previous month is not necessarily the same as having zero sales; keeping NA can be more accurate.

2. Use lead() in R to look at the next value

lead() is the counterpart to lag(). It shifts values in the opposite direction and returns a later observation for the current row. The final row in each sequence normally receives NA, because there is no next value.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(next_sales = lead(sales)) |>
  ungroup()

Use lead() when you want to compare the current record with the next record, identify what happens in the next period, or create a target variable from a later observation. In predictive modelling, make sure future information is not accidentally used as an input feature when it would not be available at prediction time.

Lead by more than one observation

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(sales_next_two_periods = lead(sales, n = 2)) |>
  ungroup()

Like lag(), lead() shifts by observation count, not by a fixed calendar interval. Check the dates before interpreting the result as “next month” if the data contains gaps.

3. Calculate differences and percentage change

One of the most common applications of window functions is comparing the current value with the previous one. After creating a lagged column, subtract it from the current value to calculate an absolute change.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(
    previous_sales = lag(sales),
    sales_change = sales - previous_sales
  ) |>
  ungroup()

A positive sales_change means sales increased compared with the previous observation; a negative value means sales decreased. The first observation in each group has no previous value, so its change is missing.

Calculate percentage change

Percentage change expresses the difference relative to the previous value. The usual formula is:

(current value - previous value) / previous value * 100

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(
    previous_sales = lag(sales),
    percent_change = (sales - previous_sales) / previous_sales * 100
  ) |>
  ungroup()

Watch for division by zero: if the previous value is zero, percentage change is undefined or infinite. If zeros are possible, handle them explicitly instead of interpreting an infinite result as an ordinary percentage.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(
    previous_sales = lag(sales),
    percent_change = if_else(
      is.na(previous_sales) | previous_sales == 0,
      NA_real_,
      (sales - previous_sales) / previous_sales * 100
    )
  ) |>
  ungroup()

Here, NA_real_ makes the missing result explicitly numeric. For more complex conditional rules, see the guide to case_when() in R.

4. Rank rows in R with row_number(), min_rank(), and dense_rank()

Ranking functions assign positions based on values. They are useful for league tables, sales performance, student results, product rankings, and identifying top-performing records. In dplyr, these functions are commonly used inside mutate().

Use row_number() for unique positions

salespeople <- tibble(
  name = c("Amina", "Bilal", "Sara", "Omar", "Noor"),
  sales = c(1200, 900, 1500, 1500, 700)
)

salespeople |>
  mutate(position = row_number(desc(sales)))

row_number(desc(sales)) gives the highest sales the first position. If two people have the same value, their unique row numbers depend on their order in the vector. If tie handling matters, choose the ranking function deliberately and add a secondary sort variable when appropriate.

Use min_rank() when tied values share a rank

salespeople |>
  mutate(rank = min_rank(desc(sales)))

With min_rank(), tied values share a rank and later ranks contain gaps. For example, two observations tied for first place are both rank 1, and the next observation is rank 3.

Use dense_rank() to avoid gaps

salespeople |>
  mutate(rank = dense_rank(desc(sales)))

dense_rank() also gives tied observations the same rank, but it does not leave gaps. If two observations share first place, the next distinct value receives rank 2.

Choose a ranking function

FunctionHow ties are handledBest used when
row_number()Each observation gets a unique row numberYou need a unique sequence or one row per position
min_rank()Tied values share rank; later ranks have gapsYou want competition-style rankings
dense_rank()Tied values share rank; no gapsYou want ranks for distinct value levels
percent_rank()Converts rank to a relative position from 0 to 1You want a relative ranking measure
cume_dist()Reports the proportion of values less than or equal to the current value, according to orderingYou want a cumulative distribution position

For top-N tasks, ranking can also be combined with slice_max() and slice_min(). Use the approach that makes the intended treatment of ties clearest.

5. Calculate cumulative totals with cumsum(), cummin(), and cummax()

Cumulative functions track a result as you move through a sequence. A cumulative sum, often called a running total, adds the current value to all earlier values in the ordered sequence.

Running total with cumsum()

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(running_sales = cumsum(sales)) |>
  ungroup()

For each salesperson, the running total starts at the first available row and grows as more monthly sales are included. Grouping means that Amina's total does not include Bilal's or Sara's sales.

Track the running maximum or minimum

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(
    best_sales_so_far = cummax(sales),
    lowest_sales_so_far = cummin(sales)
  ) |>
  ungroup()

cummax() records the highest value encountered so far, while cummin() records the lowest. These are useful for monitoring a running best performance, maximum account balance, or lowest observed cost.

Calculate a running average

There is no need to calculate each running average manually. You can divide the cumulative sum by the number of observations encountered so far.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(
    running_total = cumsum(sales),
    observations_so_far = row_number(),
    running_average = running_total / observations_so_far
  ) |>
  ungroup()

This simple running average assumes each row contributes one observation and that missing values have been handled appropriately. If rows may contain missing sales values, decide whether to exclude, replace, or otherwise handle them before interpreting the running statistics.

6. Use window functions with group_by()

group_by() changes the scope of many dplyr calculations. Without grouping, lag() and cumsum() operate over the entire vector. With grouping, they operate separately for each group and restart at the beginning of each group.

Compare each salesperson with their own previous month

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(
    previous_sales = lag(sales),
    change = sales - previous_sales,
    running_total = cumsum(sales)
  ) |>
  ungroup()

All three calculations are performed separately for each salesperson. When a new salesperson begins, the lagged value starts as missing and the cumulative total starts with that person's first sales value.

Rank sales within each region

sales_data |>
  group_by(region) |>
  mutate(region_rank = min_rank(desc(sales))) |>
  ungroup()

This assigns a rank to each salesperson's sales within their region rather than comparing everyone across the whole dataset. For a summary of each region, use group_by() and summarise(); use a window function when you want each original row to remain available.

Use more than one grouping variable

You can group by several columns. For example, if a dataset contains both product and region, you may want each product's running total to restart separately within each region.

transactions |>
  arrange(region, product, date) |>
  group_by(region, product) |>
  mutate(running_units = cumsum(units)) |>
  ungroup()

This code assumes your dataset has region, product, date, and units columns. Replace these names with the actual column names in your data.

7. Why row order matters

Sequence-based window functions operate on the order of the vector they receive. If rows are not sorted correctly, lag(), lead(), and cumulative calculations can return valid-looking but incorrect results for the question you intended to answer.

Sort by date before using lag()

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(previous_sales = lag(sales)) |>
  ungroup()

Here, arrange(salesperson, date) explicitly sorts the rows. If your data has a timestamp and multiple records can occur at the same time, consider an additional column to break ties consistently.

Row position is not the same as elapsed time

lag(sales) means “the previous row's sales,” not automatically “sales exactly one calendar month ago.” If a month is missing, the previous row may be two or more months earlier. To compare observations across fixed periods, inspect the date coverage and use an appropriate date-based workflow.

Data-quality check: before calculating time-based differences, check for duplicate dates, missing periods, and inconsistent date formats. A good sequence calculation depends on a meaningful sequence in the input data.

8. Compare each row with a group average

Not all window calculations are about neighbouring rows. You can compare every row with a statistic calculated over its group. For example, a sales record can be compared with the average sales for its region while keeping every salesperson's row.

sales_data |>
  group_by(region) |>
  mutate(
    region_average = mean(sales, na.rm = TRUE),
    difference_from_average = sales - region_average
  ) |>
  ungroup()

Every row receives the average sales for its region. The difference is positive when the individual sales value is above the regional average and negative when it is below the average.

Calculate a standardised score within a group

sales_data |>
  group_by(region) |>
  mutate(
    region_mean = mean(sales, na.rm = TRUE),
    region_sd = sd(sales, na.rm = TRUE),
    sales_z_score = (sales - region_mean) / region_sd
  ) |>
  ungroup()

A z-score describes how far a value is from its group's mean in standard-deviation units. This example is illustrative: if a group has only one observation or no variation, the standard deviation can be missing or zero, so production code should handle those cases explicitly.

For calculations that reduce the data to one row per group instead, review grouped summaries in dplyr. To apply the same calculation across many measurement columns, see across() in R.

9. Window functions for time-series analysis in R

Window functions are useful in time-series analysis because they can create variables that describe how a measurement changes over time. They are often used in exploratory analysis and as building blocks for forecasting datasets.

Example: monthly revenue change

monthly_revenue |>
  arrange(month) |>
  mutate(
    previous_revenue = lag(revenue),
    revenue_change = revenue - previous_revenue,
    revenue_growth_pct = (revenue - previous_revenue) / previous_revenue * 100
  )

This assumes monthly_revenue has one observation per month and columns named month and revenue. If the data contains multiple stores, companies, or products, group by that identifier and arrange by date within each group before calculating lagged values.

Example: a simple rolling-window feature

A rolling average uses a fixed number of recent observations rather than every observation from the beginning of the sequence. Base functions such as cumsum() create cumulative values, not fixed-width rolling windows. For a rolling mean, a package such as slider can be used.

# Install once if needed:
# install.packages("slider")
library(dplyr)
library(slider)

monthly_revenue |>
  arrange(month) |>
  mutate(
    rolling_3_month_mean = slide_dbl(
      revenue,
      mean,
      .before = 2,
      .complete = TRUE,
      na.rm = TRUE
    )
  )

With .before = 2, the calculation considers the current observation and up to two previous observations. With .complete = TRUE, the result remains missing until the full three-observation window is available. If there are multiple independent time series, calculate the rolling feature separately within each series.

Avoid future-data leakage in machine learning

When building forecasting or predictive models, a feature must use only information that would be available at the time a prediction is made. A lagged value is often suitable for historical features, whereas a lead value generally contains future information. Using future values in model training can make performance look much better than it would be in real deployment.

10. Practical applications of window functions

Business analytics and sales reporting

  • Compare current revenue with the previous period using lag().
  • Calculate running revenue and units sold with cumsum().
  • Rank employees or products within a region using dense_rank().
  • Compare each salesperson's results with the regional average.

Finance and investment analysis

  • Calculate period-over-period changes in a stock price or trading volume.
  • Track a running maximum or minimum using cummax() and cummin().
  • Create historical features from previous observations, after sorting by date.
  • Rank securities or portfolios by a chosen metric within a defined date or sector group.

For financial time series, verify that prices are sorted by date and that comparisons use the intended price field and time interval. A row-based lag does not automatically account for trading calendars or missing observations.

Education and student performance

  • Rank students by assessment score.
  • Compare a student's current score with a previous test.
  • Calculate cumulative attendance or credits completed.
  • Compare each student's result with a class or subject average.

Operations and customer analytics

  • Track cumulative orders or production output.
  • Compare a customer's current purchase with their previous purchase.
  • Rank products by sales within a store or category.
  • Monitor delivery times against a running best or group benchmark.

These methods fit into broader dplyr workflows: use filter() to keep records meeting a condition, arrange() to establish row order, and mutate() to create the calculated variables.

11. Window functions vs summarise() in dplyr

Window functions and grouped summaries both help analyse data, but they produce different shapes of output.

TaskExampleTypical output
Add previous sales to each recordmutate(previous = lag(sales))One row per original record
Add a running total to each recordmutate(total = cumsum(sales))One row per original record
Calculate one average per regiongroup_by(region) |> summarise(avg = mean(sales))Usually one row per region
Keep each salesperson and add their region averagegroup_by(region) |> mutate(avg = mean(sales))One row per original record

Use summarise() when the desired output is a compact table of group-level results. Use mutate() with a window calculation when you need row-level details and an additional calculated column.

12. Common window-function mistakes and how to fix them

Mistake 1: forgetting to sort the data

Problem: lag() returns a previous row, but the rows are not in chronological order.

# Safer: make the sequence explicit
monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(previous_sales = lag(sales)) |>
  ungroup()

Mistake 2: forgetting to group independent sequences

Problem: the first row for a new salesperson uses the previous salesperson's value.

Fix: use group_by(salesperson) before the window calculation, then use ungroup() afterward if you no longer need grouped behaviour.

Mistake 3: expecting lag() to mean one calendar month

Problem: the previous row is not always the previous calendar month when periods are missing or irregular.

Fix: check date coverage and decide how missing periods should be handled before calculating period-over-period metrics.

Mistake 4: confusing rank() and row_number()

Problem: tied values receive a different ranking than expected.

Fix: use row_number() for unique positions, min_rank() for tied ranks with gaps, or dense_rank() for tied ranks without gaps.

Mistake 5: dividing by zero in percentage-change calculations

Problem: a previous value of zero creates an undefined or infinite percentage change.

Fix: add a condition for zero and missing previous values, and decide how such cases should be reported in the final analysis.

Mistake 6: expecting a running total to reset automatically by category

Problem: cumsum() calculates across the whole vector rather than restarting for each independent entity.

Fix: group by the relevant identifier before using cumsum(), and arrange the rows into the desired sequence.

13. Practice exercises: window functions in R

Try the following exercises using monthly_sales. Expand each answer after attempting the code yourself.

Exercise 1: Add the previous month's sales for each salesperson

Sort by salesperson and date, then create a column called previous_sales.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(previous_sales = lag(sales)) |>
  ungroup()
Exercise 2: Calculate the absolute change from the previous month

Create a column named change by subtracting the previous month's sales from current sales.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(change = sales - lag(sales)) |>
  ungroup()
Exercise 3: Rank sales from highest to lowest

Add a column called sales_rank. Tied sales should share a rank and the next rank should have no gap.

monthly_sales |>
  mutate(sales_rank = dense_rank(desc(sales)))
Exercise 4: Calculate a running total for each salesperson

Create a cumulative sales column that restarts for each salesperson.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(running_total = cumsum(sales)) |>
  ungroup()
Exercise 5: Compare sales with the salesperson's next observation

Create a column called next_sales that contains the next sales value within each salesperson's sequence.

monthly_sales |>
  arrange(salesperson, date) |>
  group_by(salesperson) |>
  mutate(next_sales = lead(sales)) |>
  ungroup()

Frequently asked questions about window functions in R

dplyr FAQ

What are window functions in R?

Window functions calculate a value for each row using information from other rows, often neighbouring rows or all rows in a group. Unlike summarise(), they usually keep the original number of rows.

How do I use lag() in dplyr?

Use lag(column) to return the previous value of a vector. For time-series comparisons, arrange the data by date first and use group_by() when each entity, such as a product or customer, should have its own sequence.

What is the difference between lag() and lead() in R?

lag() shifts values backward so the current row can be compared with a previous observation. lead() shifts values forward so the current row can be compared with a subsequent observation.

How do I rank values in R with dplyr?

Use row_number(), min_rank(), or dense_rank() inside mutate(). row_number() assigns a unique position, min_rank() leaves gaps after ties, and dense_rank() does not leave gaps.

How do I calculate a cumulative sum in R?

Use cumsum(column) inside mutate(), for example mutate(running_total = cumsum(sales)). Sort the rows into the intended order first so the cumulative total follows the correct sequence.

What is the difference between a window function and summarise()?

A window function generally returns one result for each input row, while summarise() usually returns one row per group. Use window functions when you need row-level comparisons alongside the original observations.

Can window functions be used with group_by()?

Yes. Grouping makes functions such as lag(), lead(), rank(), and cumsum() operate separately within each group. Arrange rows within each group first when sequence matters.

Do window functions require dates?

No. They work with any ordered or grouped vector. Dates are common in time-series analysis, but you can also rank employees, compare consecutive transactions, or calculate running totals by product.

Key takeaways

  • Window functions calculate row-level results using information from other rows.
  • Use lag() for previous values and lead() for subsequent values.
  • Use row_number(), min_rank(), and dense_rank() for different ranking requirements.
  • Use cumsum(), cummin(), and cummax() for cumulative calculations.
  • Sort the data before sequence-based calculations and group by identifiers when each series should be handled independently.
  • Use window functions with mutate() when you want to keep the original rows; use summarise() when you want grouped summary rows.

Continue learning dplyr in R

Build on this guide with other lessons in the dplyr tutorial: