Methods for computing lags and differences on xts objects. This provides similar functionality as the zoo counterparts, but with some different defaults.
Arguments
- x
An xts object.
- k
Number of periods to shift.
- na.pad
Should
NAbe added so the result has the same number of observations asx?- ...
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?
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.
Examples
x <- xts(1:10, Sys.Date()+1:10)
lag(x) # currently using xts-style positive k
#> [,1]
#> 2026-09-29 NA
#> 2026-09-30 1
#> 2026-10-01 2
#> 2026-10-02 3
#> 2026-10-03 4
#> 2026-10-04 5
#> 2026-10-05 6
#> 2026-10-06 7
#> 2026-10-07 8
#> 2026-10-08 9
lag(x, k=2)
#> [,1]
#> 2026-09-29 NA
#> 2026-09-30 NA
#> 2026-10-01 1
#> 2026-10-02 2
#> 2026-10-03 3
#> 2026-10-04 4
#> 2026-10-05 5
#> 2026-10-06 6
#> 2026-10-07 7
#> 2026-10-08 8
lag(x, k=-1, na.pad=FALSE) # matches lag.zoo(x, k=1)
#> [,1]
#> 2026-09-29 2
#> 2026-09-30 3
#> 2026-10-01 4
#> 2026-10-02 5
#> 2026-10-03 6
#> 2026-10-04 7
#> 2026-10-05 8
#> 2026-10-06 9
#> 2026-10-07 10
diff(x)
#> [,1]
#> 2026-09-29 NA
#> 2026-09-30 1
#> 2026-10-01 1
#> 2026-10-02 1
#> 2026-10-03 1
#> 2026-10-04 1
#> 2026-10-05 1
#> 2026-10-06 1
#> 2026-10-07 1
#> 2026-10-08 1
diff(x, lag=1)
#> [,1]
#> 2026-09-29 NA
#> 2026-09-30 1
#> 2026-10-01 1
#> 2026-10-02 1
#> 2026-10-03 1
#> 2026-10-04 1
#> 2026-10-05 1
#> 2026-10-06 1
#> 2026-10-07 1
#> 2026-10-08 1
diff(x, diff=2)
#> [,1]
#> 2026-09-29 NA
#> 2026-09-30 NA
#> 2026-10-01 0
#> 2026-10-02 0
#> 2026-10-03 0
#> 2026-10-04 0
#> 2026-10-05 0
#> 2026-10-06 0
#> 2026-10-07 0
#> 2026-10-08 0
diff(diff(x))
#> [,1]
#> 2026-09-29 NA
#> 2026-09-30 NA
#> 2026-10-01 0
#> 2026-10-02 0
#> 2026-10-03 0
#> 2026-10-04 0
#> 2026-10-05 0
#> 2026-10-06 0
#> 2026-10-07 0
#> 2026-10-08 0