【问题标题】:No result when wrapping working `forecast()` statement in `tryCatch()`在 `tryCatch()` 中包装工作`forecast()` 语句时没有结果
【发布时间】: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


【解决方案1】:

我认为通过设置options(warn=-1) 来抑制警告并生成警告。我可以模拟你在这里看到的行为。

创建一个生成警告并返回 99 但警告被选项抑制的函数:

> foo=function(){o=options()$warn; options(warn=-1);warning("Yikes!");options(warn=o);return(99)}

这似乎运行良好:

> foo()
[1] 99

我可以在一个简单的tryCatch 中运行它:

> tryCatch(foo())
[1] 99

但是如果我添加 warning 子句,警告就会被困住:

> tryCatch(foo(),warning=function(w){message(w)})
Yikes!> 

虽然它似乎仍然在没有警告的情况下运行:

> foo()
[1] 99

我不确定解决方案是什么...抱歉...也许让编写试图抑制警告的代码的人重写它以改用suppressWarnings

> foo=function(){suppressWarnings({warning("Yikes!")}) ; return(99)}
> foo()
[1] 99
> tryCatch(foo(),warning=function(w){message(w)})
[1] 99

【讨论】:

  • 感谢您的解释,这澄清了正在发生的事情。
  • 仅供参考:forecast 包的作者将此添加到他的 GitHub 问题列表中。更多信息请通过github.com/robjhyndman/forecast/issues/55
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 2013-04-12
  • 2023-03-27
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多