【发布时间】:2014-02-12 08:48:30
【问题描述】:
我有大量时间序列,我想为其生成预测。为了自动生成最佳预测,我想应用一些模型,例如 auto.arima、ets、(s)naive、神经网络等。不幸的是,当它遍历时间序列时,一些模型会失败,这会停止R脚本的执行。为了使它更健壮,我开始使用tryCatch();我的主要目标是让脚本继续没有必要捕获错误。执行代码时,tryCatch() 中的forecast() 无法产生正确的预测。
请在下面找到我遇到的错误的可重现示例。
历史时间序列:
ts <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 9, 10, 10, 16, 7, 13, 0, 9, 1, 11, 2, 11, 3,
11, 4, 1, 20, 13, 13, 13, 9, 14, 16, 16, 18, 17, 20, 18, 19,
16, 16, 16, 15, 14, 27, 24, 35, 8, 18, 21, 20, 19, 22, 18, 21,
19, 24, 33, 23, 18, 26, 18, 17, 19, 19, 22, 19, 24, 29, 29, 18
), .Tsp = c(2025.25, 2032.16666666667, 12), class = "ts")
以下代码行产生正确的预测:
fcast_arima <- forecast(auto.arima(ts),h=4)
fcast_arima
Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
Apr 2032 24.69032 18.57094 30.80971 15.33153 34.04911
May 2032 25.00539 18.84018 31.17061 15.57651 34.43428
Jun 2032 25.32046 19.10975 31.53118 15.82200 34.81893
Jul 2032 25.63554 19.37966 31.89141 16.06800 35.20307
当我将相同的代码包装到 tryCatch 行时,它无法生成预测,请参见下面的示例:
fcast_arima <- tryCatch({ fcast_arima <- forecast(auto.arima(ts),h=4)}, warning = function(warningcondition) {message(warningcondition)}, error = function(errorcondition) {message(errorcondition)}, finally={})
p-value smaller than printed p-value
fcast_arima
NULL
谁能解释为什么没有tryCatch() 的代码在tryCatch() 中不能正常工作?
【问题讨论】:
-
为什么不直接使用
try(forecast(auto.arima(ts),h=4))? -
您的方法有两个问题: 1. 您的警告处理程序返回
NULL。也许demo(error.catching)可以帮助你。 2. 我不明白预测的警告。这没有意义。 -
警告来自
auto.arima(ts),但仅当在带有警告处理程序的tryCatch表达式中运行时。tryCatch(auto.arima(ts),warning=function(w){cat("Warning: ");message(w)})
标签: r try-catch forecasting