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

时间:2015-05-09 12:25:08

标签: r dynamic linear-regression predict

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

y_t = a*x1_t + b*x2_t + ... + c*y_(t-1).

y_t将被预测,x1_tx2_t将被给予,y_(t-1)也是如此。

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

我找到了this,这似乎是一个非常类似的问题,但它并没有帮助我解决自己的问题。

这是我面临的问题(基本上是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 

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

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

1 个答案:

答案 0 :(得分:4)

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