Is there a utility to run regressions using xts objects of the following type:
lm(y ~ lab(x, 1) + lag(x, 2) + lag(x,3), data=as.data.frame(coredata(my_xts)))
where my_xts
is an xts
object that contains an x
and a y
. The point of the question is is there a way to avoid doing a bunch of lags and merges to have a data.frame
with all the lags? I think that the package dyn
works for zoo
objects so i would expect it to work the same way with xts
but though there might be something updated.
The dyn and dynlm packages can do that with zoo objects. In the case of dyn just write dyn$lm
instead of lm
and pass it a zoo object instead of a data frame.
Note that lag in xts works the opposite of the usual R convention so if x is of xts class then lag(x, 1) is the same as lag(x, -1) if x were of zoo or ts class.
> library(xts)
> library(dyn)
> x <- xts(anscombe[c("y1", "x1")], as.Date(1:11)) # test data
> dyn$lm(y1 ~ lag(x1, -(1:3)), as.zoo(x))
Call:
lm(formula = dyn(y1 ~ lag(x1, -(1:3))), data = as.zoo(x))
Coefficients:
(Intercept) lag(x1, -(1:3))1 lag(x1, -(1:3))2 lag(x1, -(1:3))3
3.80530 0.04995 -0.12042 0.46631
Since you are already removing the data from the xts environment, I'm not using any xts features here. There is an embed
function that will construct a "lagged" matrix to any desired degree. (I never understood the time-series lag
function.) (the order of the embed-lagged variables is reversed from what I would have expected.)
embed(1:6, 3)
#--------
[,1] [,2] [,3]
[1,] 3 2 1
[2,] 4 3 2
[3,] 5 4 3
[4,] 6 5 4
#Worked example ... need to shorten the y variable
y <- rnorm(20)
x <- rnorm(20)
lm( tail(y, 18) ~ embed(x, 3) )
#-------------------
Call:
lm(formula = tail(y, 18) ~ embed(x, 3))
Coefficients:
(Intercept) embed(x, 3)1 embed(x, 3)2 embed(x, 3)3
-0.12452 -0.34919 0.01571 0.01715
It was a relief to note that after changing the lags to match those used by @GGrothendieck that we get identical results:
lm( tail(xx[,"y1"], NROW(xx)-3) ~ embed(xx[,"x1"], 4)[,2:4] )
Call:
lm(formula = tail(xx[, "y1"], NROW(xx) - 3) ~ embed(xx[, "x1"],
4)[, 2:4])
Coefficients:
(Intercept) embed(xx[, "x1"], 4)[, 2:4]1 embed(xx[, "x1"], 4)[, 2:4]2
3.80530 0.04995 -0.12042
embed(xx[, "x1"], 4)[, 2:4]3
0.46631
来源:https://stackoverflow.com/questions/11893138/regressions-with-xts-in-r