diff {base}R Documentation

Lagged Differences

Description

Returns suitably lagged and iterated differences of “neighbours” in a often time-series alike sequences, in the simplest case, x[2:n] - x[1:(n-1)].

Usage

diff(x, ...)

## Default S3 method:
diff(x, lag = 1, differences = 1, ...)

## S3 method for class 'POSIXt'
diff(x, lag = 1, differences = 1, ...)

## S3 method for class 'Date'
diff(x, lag = 1, differences = 1, ...)

Arguments

x

a numeric vector or matrix containing the values to be differenced.

lag

an integer indicating which lag to use.

differences

an integer indicating the order of the difference.

...

further arguments to be passed to or from methods.

Details

diff is a generic function with a default method and ones for classes "ts", "POSIXt" and "Date".

NA's propagate.

Value

If x is a vector of length n and differences = 1, then the computed result is equal to the successive differences x[(1+lag):n] - x[1:(n-lag)].

If difference is larger than one this algorithm is applied recursively to x. Note that the returned value is a vector which is shorter than x.

If x is a matrix then the difference operations are carried out on each column separately, resulting in a matrix with the same number of columns (and nrow(x) - lag rows (when differences == 1).

References

Becker R. A., Chambers J. M., Wilks A. R. (1988). The New S Language. Chapman and Hall/CRC, London. ISBN 053409192X.

See Also

diff.ts, diffinv.

Examples

diff(1:10, 2)
diff(1:10, 2, 2)
x <- cumsum(cumsum(1:10))
diff(x, lag = 2)
diff(x, differences = 2)

diff(.leap.seconds)
## allows to pass units via ... to difftime()
diff(.leap.seconds, units = "weeks")
diff(as.Date(.leap.seconds), units = "weeks")

[Package base version 4.6.0 Index]