[英]R: Dynamic linear regression with dynlm package, how to predict()?
我正在嘗試建立一個動態回歸模型,到目前為止,我是使用dynlm軟件包完成的。 基本上模型看起來像這樣
y_t = a*x1_t + b*x2_t + ... + c*y_(t-1).
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
當然,我可以只使用自己的預測函數,但是問題是我的真實模型將具有更多的變量(隨着我使用步進函數根據AIC優化模型,這些變量甚至可能會有所不同),這就是為什么我想使用predict()
函數。
有什么想法,如何解決呢?
不幸的是, dynlm
包不提供predict()
方法。 目前,程序包將數據預處理(了解d()
, L()
, trend()
, season()
等功能)與模型擬合(本身不了解功能)完全分開了。 我的心願單上有一個predict()
方法,但是到目前為止,我還沒有寫完一個方法,因為接口的靈活性允許這么多的模型,而這些模型並不是很簡單。 同時,我可能應該添加一個在繼承找到lm
方法之前引發警告的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.