Learn R Programming

xts (version 0.14.1)

lag.xts: Lags and Differences of xts Objects

Description

Methods for computing lags and differences on xts objects. This provides similar functionality as the zoo counterparts, but with some different defaults.

Usage

# S3 method for xts
lag(x, k = 1, na.pad = TRUE, ...)

# S3 method for xts diff( x, lag = 1, differences = 1, arithmetic = TRUE, log = FALSE, na.pad = TRUE, ... )

Value

An xts object with the desired lag and/or differencing.

Arguments

x

An xts object.

k

Number of periods to shift.

na.pad

Should NA be added so the result has the same number of observations as x?

...

Additional arguments.

lag

Period to difference over.

differences

Order of differencing.

arithmetic

Should arithmetic or geometric differencing be used?

log

Should (geometric) log differences be returned?

Author

Jeffrey A. Ryan

Details

The primary motivation for these methods was to take advantage of a faster C-level implementation. Another motivation was to make lag() behave using standard sign for k. Both zoo's lag() method and lag.default() require a negative value for k in order to shift a series backward. So k = 1, shifts the series forward one observation. This is especially confusing because k = 1 is the default for those functions. When x is an xts object, lag(x, 1) returns an object where the value at time 't' is the value at time 't-1' in the original object.

Another difference is that na.pad = TRUE by default, to better reflect the transformation visually and for functions the require positional alignment of data.

Set options(xts.compat.zoo.lag = TRUE) to use make lag.xts() consistent with lag.zoo() by reversing the sign of k and setting na.pad = FALSE.

References

https://en.wikipedia.org/wiki/Lag

Examples

Run this code

x <- xts(1:10, Sys.Date()+1:10)
lag(x)    # currently using xts-style positive k 

lag(x, k=2)

lag(x, k=-1, na.pad=FALSE) # matches lag.zoo(x, k=1)

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

Run the code above in your browser using DataLab