R:使用 dynlm 包进行动态线性回归,如何预测()?

sch*_*uk5 4 r dynamic linear-regression predict

我正在尝试构建一个动态回归模型,到目前为止我是用 dynlm 包完成的。基本上模型看起来像这样

y_t = a*x1_t + b*x2_t + ... + c*y_(t-1).
Run Code Online (Sandbox Code Playgroud)

y_t应预测,x1_t并且x2_t将给予,所以是y_(t-1)

使用 dynlm 包构建模型工作正常,但是当涉及到预测时,y_t我感到困惑......

我发现了这个,这似乎是一个非常相似的问题,但它并没有帮助我处理我自己的问题。

这是我面临的问题(基本上是什么predict(),似乎很奇怪。请参阅评论!):

library(dynlm)

# Create Data
set.seed(1)
y <- arima.sim(model = list(ar = c(.9)), n = 11) #Create AR(1) dependant variable
A <- rnorm(11) #Create independent variables
B <- rnorm(11)
y <- y + .5 * A + .2 * B #Add relationship to independent variables 
data = cbind(y, A, B)

# subset used for the fitting of the model
reg <- data[1:10, ]


# Fit dynamic linear model
model <- dynlm(y ~ A + B + L(y, k = 1), data = reg)  # dynlm
model

# Time series regression with "zooreg" data:
# Start = 2, End = 11
#
# Call:
# dynlm(formula = y ~ A + B + L(y, k = 1), data = reg)

# Coefficients:
# (Intercept)            A            B  L(y, k = 1)  
#      0.8930      -0.2175       0.2892       0.5176  


# subset last two rows.
# the last row (r11) for which y_t shall be predicted, where from the same time A and B are input for the prediction
# and the second last row (r10), so y_(t-1) can be input for the model as well
pred <- as.data.frame(data[10:11, ])

# prediction using predict()
predict(model, newdata = pred)

#    1        2 
# 1.833134 1.483809 

# manual calculation of prediction of y in r11 (how I thought it should be...), taking y_(t-1) as input
predicted_value <- model$coefficients[1] + model$coefficients[2] * pred[2, 2] + model$coefficients[3] * pred[2, 3] + model$coefficients[4] * pred[1, 1]
predicted_value
# (Intercept) 
#    1.743334 

# and then what gives the value from predict() above taking y_t into the model (which is the value that should be predicted and not y_(t-1))
predicted_value <- model$coefficients[1] + model$coefficients[2] * pred[2, 2] + model$coefficients[3] * pred[2, 3] + model$coefficients[4] * pred[2, 1]
predicted_value
# (Intercept) 
#    1.483809 
Run Code Online (Sandbox Code Playgroud)

当然我可以只使用我自己的预测函数,但问题是我的真实模型会有更多的变量(甚至可以随着我根据 AIC 使用阶跃函数优化模型而变化),这就是为什么我想用这个predict()功能。

任何想法,如何解决这个问题?

Ach*_*eis 5

不幸的是,该dynlm包没有提供predict()方法。此刻的包装完全分离的数据前处理(其知道的功能,如d()L()trend()season()等等)和模型拟合(其本身是不知道的函数)。一种predict()方法一直在我的愿望清单上,但到目前为止我还没有写出一个方法,因为界面的灵活性允许有很多模型,但要做什么并不是很简单。同时,我可能应该添加一个在lm通过继承找到该方法之前抛出警告的方法。