lag( ) / lead( )
Shift a column’s values backward or forward by n rows. lag() and lead() are from the dplyr package, which is part of the tidyverse.
Required Library
install.packages("tidyverse")
library(tidyverse)Syntax
lag() and lead() work on a vector — usually a data frame column referenced inside mutate(), so the shifted result is stored back as a new column.
lag(x, n = 1)lag(x) shifts a column’s values backward: each row gets the value from n rows before it. The first n rows have nothing to look back to, so they become NA.
lead(x, n = 1)lead(x) shifts a column’s values forward: each row gets the value from n rows after it. The last n rows have nothing to look ahead to, so they become NA.
lag() / lead()?
Use lag() and lead() inside mutate() when you need to compare a row to its neighbor — for example the change since the previous timepoint. Both depend on row order, not on values, so arrange() your data first.
Examples
Add the previous value with lag()
Compute the change since the previous timepoint
Subtracting lag() from the current value gives the change between consecutive dissolution readings — the realistic use case for lag().
Add the next value with lead()
lead() mirrors lag(), looking forward instead of backward.
Shift by more than one row with n
Fill the boundary NA with default
The first row of each tablet has no earlier value to look back to, so lag() returns NA there. Use default to fill that gap instead — here, treating the start of dissolution as 0%.
Argument Overview
Required arguments must be included when using a function while optional arguments can be included on demand.
x — vector to shift vector Required
The column (or vector) whose values should be shifted. Almost always used inside mutate().
dissolution %>% mutate(previous_pct = lag(pct_dissolved))Data Types: any vector type
n — number of positions to shift integer Optional
How many rows to look back (lag()) or ahead (lead()). Default is 1, meaning “the immediately previous/next row”.
dissolution %>% mutate(pct_two_steps_ago = lag(pct_dissolved, n = 2))
Data Types: integer · Default: 1
default — value for the introduced NA any Optional
The value used for rows that have no previous/next row to pull from (the start of the data for lag(), the end for lead()). Defaults to NA.
dissolution %>% mutate(previous_pct = lag(pct_dissolved, default = 0))
Data Types: same type as x · Default: NA
order_by — column defining the shift order column name Optional
By default, lag()/lead() shift by current row order. If the data isn’t already arranged the way you need, pass a column here instead of arranging first.
dissolution %>% mutate(previous_pct = lag(pct_dissolved, order_by = time_min))
Data Types: column name · Default: NULL (uses row order)