我是R的新手并且发现这个网站非常有用,所以这涵盖了我的问题的后半部分(每个帖子一个问题) . 感谢您提前给予的帮助 .
Background: 我正在绘制历史数据,其中多个预测覆盖了视觉准确性检查 . 当在'observations'的x轴上显示时,这很有效 . 但是,当在x轴上绘制日期时,数据更容易理解,所以我使用ts()创建了一个时间序列,并按预期绘制了时间序列数据 . 但是,(A)它没有在时间尺度上绘制预测数据,因为它们不是时间序列; (B)我不确定如何强制x轴加1年以允许显示预测 .
Question: (A)如何将原始时间戳恢复为预测数据?我知道我可以手动重新创建时间序列,但这在预测的每次迭代中都是必需的 . 我考虑使用forecast()而不是predict(),但是额外的预测迭代仍然存在不是时间序列的相同问题 . Is there a simple way to restore the original time stamp to the forecast data?
require(forecast) [EDITED for clarity]
data <- rep(cos(1:52*(3.1416/26)),5)*100+1000
arima.ts <- ts(data,start=c(2009,1),frequency=52) #not plotted as time series
# Create the current fit on data and predict one year out
plot(arima.ts, type="l", xlab="weeks", ylab="counts",
main="Overlay forecasts & actuals",
sub="green=FIT(1-105,by 16) wks back & PREDICT(26) wks, blue=52 wks")
############## This plotted correctly as "Arima(data),..."
arima.fit <- auto.arima(tail(arima.ts,156))
arima.pred <- predict(arima.fit, n.ahead=52)
lines(arima.pred$pred, col="blue")
lines(arima.pred$pred+2*arima.pred$se, col="red")
lines(arima.pred$pred-2*arima.pred$se, col="red")
# Loop back and perform comparison plotting of forecast to actuals
for (j in seq(1,105,by=16)) {
result <- tryCatch({
############## This plotted correctly as "Arima(head(data,-j),..."
arima1.fit <- auto.arima(head(tail(arima.ts,-j),156))
arima1.pred <- predict(arima1.fit, n.ahead=52)
lines(arima1.pred$pred, col="green", lty=(numtests %% 6) + 1 )
}, error = function(e) {return(e$message)}) ## Trap errors
}
2 回答
正在解决的核心问题是"how to restore the original time stamps to the forecast data" . 我通过试验和错误学到的是"configure, then never loose the time series attribute",通过应用这些步骤:
1: Make a time series 使用ts()命令创建时间系列 .
2: Subset a time series 使用'window()'在'for()'循环中创建时间系列的子集 . 在数据上使用'start()'和'end()'来显示时间轴位置 .
3: Forecast a time series 使用按时间序列操作的'forecast()'或'predict()' .
4: Plot a time series 绘制时间序列时,时间轴将使用lines()命令正确对齐其他数据 . {绘图选项是用户偏好 . }
这会使预测在正确的时间轴位置上绘制在历史数据上 .
如果您需要进一步详细说明,请与我们联系 .