regressions with xts in R

人盡茶涼 提交于 2019-12-03 05:01:46
G. Grothendieck

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  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!