R避免“重新启动中断的承诺评估”警告 [英] R avoiding "restarting interrupted promise evaluation" warning

查看:3595
本文介绍了R避免“重新启动中断的承诺评估”警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎在一个函数内,当您评估多次产生错误的表达式时,会收到警告重新启动中断承诺评估。例如:

It seems that within a function, when you evaluate an expression that yields an error more than once, you get the warning restarting interrupted promise evaluation. For instance:

foo <- function() stop("Foo error")
bar <- function(x) {
    try(x)
    x
}
bar(foo())

Error in foo() : Foo error
Error in foo() : Foo error
In addition: Warning message:
In bar(foo()) : restarting interrupted promise evaluation

如何避免此警告并正确处理?

How to avoid this warning and deal with it properly?

特别是在写入数据库的操作中,可能会遇到需要重试操作几次的锁定错误。因此,我在 tryCatch 周围创建一个包装,重新计算一个表达式,直到 n 次,直到成功:

Especially with operations like writing to a database, you might encounter locking errors that require you to retry your operation a few times. Hence I'm creating a wrapper around tryCatch that re-evaluates an expression up to n times until successful:

tryAgain <- function(expr, n = 3) {
    success <- T
    for (i in 1:n) {
        res <- tryCatch(expr,
            error = function(e) {
                print(sprintf("Log error to file: %s", conditionMessage(e)))
                success <<- F
                e
            }
        )
        if (success) break
    }
    res
}

但是,我正在加载重新启动中断的承诺评估消息:

However, I'm getting loads of restarting interrupted promise evaluation messages:

>   tryAgain(foo())
[1] "Log error to file: Foo error"
[1] "Log error to file: Foo error"
[1] "Log error to file: Foo error"
<simpleError in foo(): Foo error>
Warning messages:
1: In doTryCatch(return(expr), name, parentenv, handler) :
  restarting interrupted promise evaluation
2: In doTryCatch(return(expr), name, parentenv, handler) :
  restarting interrupted promise evaluation

理想情况下,我想避免这些消息完全而不是只是消除它们,因为我也可能想要处理来自 expr 的真实警告。

Ideally I want to avoid these messages altogether rather than just muffle them, since I might also want to handle genuine warnings coming from expr.

推荐答案

如果您想要显示每个错误消息,您也可以尝试此操作,而不需要 silent = TRUE 在任何一种情况下,您都不会收到有关承诺的消息:

You can also try this without silent=TRUE if you want each error message to show. In neither case will you get the message about promises:

foo <- function() stop("Foo error")
bar <- function(x) {
    try(eval.parent(substitute(x)), silent = TRUE)
    x
}
bar(foo())

这篇关于R避免“重新启动中断的承诺评估”警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆