Methods for computing lags and differences on xts objects. This provides similar functionality as the zoo counterparts, but with some different defaults.
An xts object.
Number of periods to shift.
Should NA be added so the result has the same number of
observations as x?
Additional arguments.
Period to difference over.
Order of differencing.
Should arithmetic or geometric differencing be used?
Should (geometric) log differences be returned?
An xts object with the desired lag and/or differencing.
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.
x <- xts(1:10, Sys.Date()+1:10)
lag(x) # currently using xts-style positive k
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 1
#> 2025-11-03 2
#> 2025-11-04 3
#> 2025-11-05 4
#> 2025-11-06 5
#> 2025-11-07 6
#> 2025-11-08 7
#> 2025-11-09 8
#> 2025-11-10 9
lag(x, k=2)
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 NA
#> 2025-11-03 1
#> 2025-11-04 2
#> 2025-11-05 3
#> 2025-11-06 4
#> 2025-11-07 5
#> 2025-11-08 6
#> 2025-11-09 7
#> 2025-11-10 8
lag(x, k=-1, na.pad=FALSE) # matches lag.zoo(x, k=1)
#> [,1]
#> 2025-11-01 2
#> 2025-11-02 3
#> 2025-11-03 4
#> 2025-11-04 5
#> 2025-11-05 6
#> 2025-11-06 7
#> 2025-11-07 8
#> 2025-11-08 9
#> 2025-11-09 10
diff(x)
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 1
#> 2025-11-03 1
#> 2025-11-04 1
#> 2025-11-05 1
#> 2025-11-06 1
#> 2025-11-07 1
#> 2025-11-08 1
#> 2025-11-09 1
#> 2025-11-10 1
diff(x, lag=1)
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 1
#> 2025-11-03 1
#> 2025-11-04 1
#> 2025-11-05 1
#> 2025-11-06 1
#> 2025-11-07 1
#> 2025-11-08 1
#> 2025-11-09 1
#> 2025-11-10 1
diff(x, diff=2)
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 NA
#> 2025-11-03 0
#> 2025-11-04 0
#> 2025-11-05 0
#> 2025-11-06 0
#> 2025-11-07 0
#> 2025-11-08 0
#> 2025-11-09 0
#> 2025-11-10 0
diff(diff(x))
#> [,1]
#> 2025-11-01 NA
#> 2025-11-02 NA
#> 2025-11-03 0
#> 2025-11-04 0
#> 2025-11-05 0
#> 2025-11-06 0
#> 2025-11-07 0
#> 2025-11-08 0
#> 2025-11-09 0
#> 2025-11-10 0