具有索引解释变量(年)的 OLS 线性模型中的预测值

Predicting values in OLS linear model with indexed explanatory variable (years)

这个问题可能有上百万种解决方法,这会使实际答案变得无关紧要,但固执会阻碍...

在试图理解时间序列的应用时,很明显,去趋势化数据使得预测未来值变得不可信。例如,使用 astsa 包中的 gtemp 数据集,需要考虑过去几十年的上升趋势:

所以我最终得到了去趋势化数据的 ARIMA 模型(正确或错误),这让我可以 "forecast" 提前 10 年:

fit = arima(gtemp, order = c(4, 1, 1))
pred = predict(fit, n.ahead = 10)

以及基于 1950 年以来的值的 OLS 趋势估计:

gtemp1 = window(gtemp, start = 1950, end = 2009)
fit2 = lm(gtemp1 ~ I(1950:2009))

问题是如何使用predict()得到未来10年线性模型部分的估计值。

如果我 运行 predict(fit2, data.frame(I(2010:2019))) 我得到 60 个值,我将得到 运行ning predict(fit2),加上错误消息:'newdata' had 10 rows but variables found have 60 rows

你需要:

dat <- data.frame(year = 1950:2009, gtemp1 = as.numeric(gtemp1))
fit2 <- lm(gtemp1 ~ year, data = dat)
unname( predict(fit2, newdata = data.frame(year = 2010:2019)) )
# [1] 0.4928475 0.5037277 0.5146079 0.5254882 0.5363684 0.5472487 0.5581289
# [8] 0.5690092 0.5798894 0.5907697

或者,如果您不想在 lm 中使用 data 参数,您需要:

year <- 1950:2009
fit2 <- lm(gtemp1 ~ year)
unname( predict(fit2, newdata = data.frame(year = 2010:2019)) )
# [1] 0.4928475 0.5037277 0.5146079 0.5254882 0.5363684 0.5472487 0.5581289
# [8] 0.5690092 0.5798894 0.5907697

为什么你的原始代码失败了

当您执行 fit2 <- lm(gtemp1 ~ I(1950:2009)) 时,lm 假设存在一个名为 I(1950:2009) 的协变量:

attr(fit2$terms, "term.labels")  ## names of covariates
# [1] "I(1950:2009)"

当您稍后进行预测时,predict 将致力于在您的新数据框中找到一个名为 I(1950:2009) 的变量。但是,请查看 newdata:

的列名
colnames( data.frame(I(2010:2019)) )
# [1] "X2010.2019"

因此,predict.lmnewdata中找不到变量I(1950:2009),那么它将使用内部模型框架fit2$model作为newdata,和 return 默认情况下的拟合值(这解释了为什么你得到 60 个值)。