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-03-06 NA
#> 2026-03-07 1
#> 2026-03-08 2
#> 2026-03-09 3
#> 2026-03-10 4
#> 2026-03-11 5
#> 2026-03-12 6
#> 2026-03-13 7
#> 2026-03-14 8
#> 2026-03-15 9
lag(x, k=2)
#> [,1]
#> 2026-03-06 NA
#> 2026-03-07 NA
#> 2026-03-08 1
#> 2026-03-09 2
#> 2026-03-10 3
#> 2026-03-11 4
#> 2026-03-12 5
#> 2026-03-13 6
#> 2026-03-14 7
#> 2026-03-15 8
lag(x, k=-1, na.pad=FALSE) # matches lag.zoo(x, k=1)
#> [,1]
#> 2026-03-06 2
#> 2026-03-07 3
#> 2026-03-08 4
#> 2026-03-09 5
#> 2026-03-10 6
#> 2026-03-11 7
#> 2026-03-12 8
#> 2026-03-13 9
#> 2026-03-14 10
diff(x)
#> [,1]
#> 2026-03-06 NA
#> 2026-03-07 1
#> 2026-03-08 1
#> 2026-03-09 1
#> 2026-03-10 1
#> 2026-03-11 1
#> 2026-03-12 1
#> 2026-03-13 1
#> 2026-03-14 1
#> 2026-03-15 1
diff(x, lag=1)
#> [,1]
#> 2026-03-06 NA
#> 2026-03-07 1
#> 2026-03-08 1
#> 2026-03-09 1
#> 2026-03-10 1
#> 2026-03-11 1
#> 2026-03-12 1
#> 2026-03-13 1
#> 2026-03-14 1
#> 2026-03-15 1
diff(x, diff=2)
#> [,1]
#> 2026-03-06 NA
#> 2026-03-07 NA
#> 2026-03-08 0
#> 2026-03-09 0
#> 2026-03-10 0
#> 2026-03-11 0
#> 2026-03-12 0
#> 2026-03-13 0
#> 2026-03-14 0
#> 2026-03-15 0
diff(diff(x))
#> [,1]
#> 2026-03-06 NA
#> 2026-03-07 NA
#> 2026-03-08 0
#> 2026-03-09 0
#> 2026-03-10 0
#> 2026-03-11 0
#> 2026-03-12 0
#> 2026-03-13 0
#> 2026-03-14 0
#> 2026-03-15 0