regressions with xts in R

前端 未结 2 790
野性不改
野性不改 2021-02-06 18:32

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)))


        
相关标签:
2条回答
  • 2021-02-06 18:57

    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  
    
    0 讨论(0)
  • 2021-02-06 19:09

    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  
    
    0 讨论(0)
提交回复
热议问题