简体   繁体   中英

Regression with lagged time time series data in R

I have two-time series data A and B. I want to execute the following linear regression in R

A ~ Lags(A, 1:2) + Lags(B, 1:2)

Can you please help me with the R code?

Using dyn and the built in BOD data frame (which contains two columns, Time and demand) we can specify the indicated lags.

Note that the dplyr package clobbers lag so just in case it is loaded we restore base lag. Note the sign needed with lag.

Using dyn$lm and zoo(BOD) will result in automatic alignment.

If BOD did not include only numeric data it would be necessary to eliminate any columns not used first; however, here BOD is entirely numeric.

library(dyn)  # also loads zoo

lag <- stats::lag
fm <- dyn$lm(demand ~ lag(demand, -(1:2)) + lag(Time, -(1:2)), zoo(BOD))
fm

giving:

Call:
lm(formula = dyn(demand ~ lag(demand, -(1:2)) + lag(Time, -(1:2))), 
    data = zoo(BOD))

Coefficients:
         (Intercept)  lag(demand, -(1:2))1  lag(demand, -(1:2))2  
             23.5410               -0.5126               -0.5071  
  lag(Time, -(1:2))1    lag(Time, -(1:2))2  
              2.4737                    NA  

This shows BOD and the model.frame and model.matrix used.

> BOD
  Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8

> model.frame(fm)
  demand lag(demand, -(1:2)).1 lag(demand, -(1:2)).2 lag(Time, -(1:2)).1 lag(Time, -(1:2)).2
3   19.0                  10.3                   8.3                   2                   1
4   16.0                  19.0                  10.3                   3                   2
5   15.6                  16.0                  19.0                   4                   3
6   19.8                  15.6                  16.0                   5                   4

> model.matrix(fm)
  (Intercept) lag(demand, -(1:2))1 lag(demand, -(1:2))2 lag(Time, -(1:2))1 lag(Time, -(1:2))2
3           1                 10.3                  8.3                  2                  1
4           1                 19.0                 10.3                  3                  2
5           1                 16.0                 19.0                  4                  3
6           1                 15.6                 16.0                  5                  4
attr(,"assign")
[1] 0 1 1 2 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM