【问题标题】:Creating a "retry" function in R在 R 中创建“重试”函数
【发布时间】:2016-05-22 20:44:39
【问题描述】:

我正在尝试做一个重试函数,它会将我想做的事情作为参数,以及在停止之前应该尝试的次数。

我想出了以下几点:

retry <- function(a, max = 10, init = 0){tryCatch({
  if(init<max) a
}, error = function(e){retry(a, max, init = init+1)})}

现在我想对其进行测试并确保它按我的预期工作,但我希望有人仔细检查一下,也许可以就我应该进一步测试的内容给我建议。

为了测试它并看看会发生什么,我这样修改了我的函数:

retry <- function(a, max = 10, init = 0){
  tryCatch({
    if(init<max) {
      print(init) # added part
      a
    }
  }, error = function(e){retry(a, max, init = init+1)})}

我正在使用stop() 生成错误并对其进行测试。它似乎或多或少地按照我的意图工作......

> retry(stop())
[1] 0
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6
[1] 7
[1] 8
[1] 9

但是……

There were 45 warnings (use warnings() to see them)
> warnings()
Messages d`avis :
1: In doTryCatch(return(expr), name, parentenv, handler) :
  restarting interrupted promise evaluation

    # (the 45 error messages are the same, the last one being the following)

45: In doTryCatch(return(expr), name, parentenv, handler) :
  restarting interrupted promise evaluation

所以我的问题:

  1. 它似乎按我的意愿工作,对吧?
  2. 我可以安全地忽略这些警告吗?

注意:警告的数量似乎取决于参数max 的值,遵循以下模式:

max   nb of warnings
1     no warning
2     1
3     3
4     6
5     10
6     15
7     21
8     28
9     36
10    45

【问题讨论】:

    标签: r error-handling


    【解决方案1】:

    你试图搞砸a 的承诺。正确的解决方案是使用substituterlang::enexpr。我已经整理了一些代码作为包retry

    library(retry)
    
    f <- function(x) {
        if (runif(1) < 0.9) {
            stop("random error")
        }
        x + 1
    }
    
    # keep retring when there is a random error
    retry(f(1), when = "random error")
    #> [1] 2
    # keep retring until a requirement is satisified.
    retry(f(1), until = function(val, cnd) val == 2)
    #> [1] 2
    # or using one sided formula
    retry(f(1), until = ~ . == 2)
    #> [1] 2
    

    【讨论】:

      【解决方案2】:

      有一个要包裹在表达式周围的 suppressWarnings() 函数:

      retry <- function(a, max = 10, init = 0){suppressWarnings( tryCatch({
        if(init<max) a
      }, error = function(e){retry(a, max, init = init+1)}))}
      

      【讨论】:

      • 这不会抑制我在使用该函数时收到的实际有用警告吗?
      • 我想你需要提出一个问题,astop 更有趣。
      猜你喜欢
      • 2023-01-05
      • 1970-01-01
      • 1970-01-01
      • 2014-07-15
      • 2022-07-05
      • 2016-06-09
      • 2019-04-28
      • 2014-09-03
      • 2021-05-30
      相关资源
      最近更新 更多