R, lag( ) has inconsistent behavior for xts and ts objects

204 views Asked by At

I would like to take a lag of an xts variable, and the lag() function returns a lag. However, if I use it on a ts variable, it gives a lead. Is this a bug, or working as intended?

library('xts')

a = as.xts(ts(c(5,3,7,2,4,8,3), start=c(1980,1), freq=4))
cbind(a, lag(a)) # provides lag 1
#         ..1 ..2
# 1980 Q1   5  NA
# 1980 Q2   3   5
# 1980 Q3   7   3
# 1980 Q4   2   7
# 1981 Q1   4   2
# 1981 Q2   8   4
# 1981 Q3   3   8
b = ts(c(5,3,7,2,4,8,3), start=c(1980,1), freq=4)
cbind(b, lag(b)) # provides lead 1
#          b lag(b)
# 1979 Q4 NA      5
# 1980 Q1  5      3
# 1980 Q2  3      7
# 1980 Q3  7      2
# 1980 Q4  2      4
# 1981 Q1  4      8
# 1981 Q2  8      3
# 1981 Q3  3     NA
1

There are 1 answers

0
HRC On BEST ANSWER

As was pointed out in the documentation from ?lag.xts, this is the intended behavior.