简体   繁体   English

R 中滞后时间序列数据的回归

[英]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和B。我想在R中执行以下线性回归

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

Can you please help me with the R code?你能帮我 R 代码吗?

Using dyn and the built in BOD data frame (which contains two columns, Time and demand) we can specify the indicated lags.使用 dyn 和内置的 BOD 数据框(包含两列,时间和需求),我们可以指定指示的滞后。

Note that the dplyr package clobbers lag so just in case it is loaded we restore base lag.请注意 dplyr package clobbers 滞后所以以防万一它被加载我们恢复基本滞后。 Note the sign needed with lag.注意滞后所需的标志。

Using dyn$lm and zoo(BOD) will result in automatic alignment.使用 dyn$lm 和 zoo(BOD) 将导致自动 alignment。

If BOD did not include only numeric data it would be necessary to eliminate any columns not used first;如果 BOD 不只包含数字数据,则有必要删除所有未首先使用的列; however, here BOD is entirely numeric.但是,这里的 BOD 完全是数字。

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 和使用的 model.frame 和 model.matrix。

> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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