diff()

diff(x, lag = 1, differences = 1)
Returns: numeric · Updated March 13, 2026 · Base Functions
arithmetic sequences base differences

The diff() function computes lagged differences between consecutive elements in a numeric vector. By default, it calculates the first-order difference (each element minus its predecessor), which is essential for analyzing changes over time, detecting trends, and computing rate of change.

Syntax

diff(x, lag = 1, differences = 1)

Parameters

ParameterTypeDefaultDescription
xnumericA numeric vector or an object that can be coerced to numeric
laginteger1The number of lags to use for computing differences
differencesinteger1The number of times differences are recursively applied

Examples

Basic usage

# Simple first-order differences
x <- c(10, 15, 13, 18, 20)
diff(x)
# [1]  5 -2  5  2

# Each element minus its predecessor
# 15-10=5, 13-15=-2, 18-13=5, 20-18=2

Computing percentage changes

# Stock prices over 5 days
prices <- c(100, 105, 102, 110, 108)

# Daily price changes
daily_change <- diff(prices)
daily_change
# [1]  5 -3  8 -2

# Percentage change (need to divide by previous value)
pct_change <- daily_change / prices[-length(prices)] * 100
pct_change
# [1]  5.000000 -2.857143  7.843137 -1.818182

Using lag parameter

x <- c(1, 3, 6, 10, 15, 21)

# Default lag=1: consecutive differences
diff(x)
# [1] 2 3 4 5 6

# Lag=2: differences between elements 2 apart
diff(x, lag = 2)
# [1] 5 7 9 11
# 6-1=5, 10-3=7, 15-6=9, 21-10=11

Using differences parameter

x <- c(1, 3, 6, 10, 15, 21)

# First-order differences (default)
diff(x)
# [1] 2 3 4 5 6

# Second-order differences (difference of differences)
diff(x, differences = 2)
# [1] 1 1 1 1
# First: 2,3,4,5,6
# Then: 3-2=1, 4-3=1, 5-4=1, 6-5=1

Common Patterns

Detecting sign changes

# Find where the direction of change flips
changes <- diff(x)
signs <- sign(changes)
which(signs[-length(signs)] != signs[-1]) + 1

Computing running totals first

# First accumulate, then diff recovers original
x <- c(10, 25, 30, 55, 60)
cumsum(x)
# [1]  10  35  65 120 180

# diff(cumsum(x)) returns x[-length(x)]
diff(cumsum(x))
# [1] 10 25 30 55

Working with time series

# Simulated daily temperatures
temps <- c(20, 22, 25, 23, 19, 21, 24)

# Identify warming/cooling trends
diff(temps)
# [1]  2  3 -2 -4  2  3

# Positive = warming, Negative = cooling

See Also