1

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
HRC
  • 107
  • 7
  • 1
    Your sentence says `lag.xts` provides a lead and `lag.ts` provides a lag, but your code comments say the opposite. Please clarify. Also note that `?lag.xts` says it uses the opposite sign convention than `lag.ts` and `lag.zoo`. – Joshua Ulrich Jun 19 '15 at 16:10
  • This seems to be a [known issue](http://grokbase.com/t/r/r-help/124cxksf5a/r-definition-of-lag-is-opposite-in-ts-and-xts-objects), but it was new for me (I use almost exclusively the xts format). Good to know – RHertel Jun 19 '15 at 16:12

1 Answers1

0

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

HRC
  • 107
  • 7