r - 在R中带有警告的函数中抑制,记录和返回值

标签 r error-handling try-catch

有一个带有警告的函数,但它不会影响最终输出。我想将警告捕获到日志中,在控制台上取消显示警告消息并返回该值。

fn1 <- function() {
    warning("this is a warning!")
    return(1)
}

我尝试了withCallingHandlers,但是警告消息仍然打印出来,并且tryCatch阻止了返回值。例如,我使用message假装保存到日志。

withCallingHandlers(expr = fn1(),
                    warning = function(w) {
                        message(paste0("saved to a file: ", w$message))
                        # write(w$message, "xxlocation")
                    }
)

输出

saved to a file: this is a warning!
[1] 1
Warning message:
In fn1() : this is a warning!

我可以使用重新启动来抑制警告,但是我的返回值也被抑制。与tryCatch非常相似:

withCallingHandlers(
    withRestarts(fn1(),
                 mufflewarn=function(msg) {
                     message(msg)
                 }),
    warning = function(w) {
        invokeRestart("mufflewarn", w$message)
    }
)

this is a warning!

有什么办法可以让我输出:

saved to a file: this is a warning!
[1] 1

最佳答案

事实证明,解决方案非常简单,只需使用suppressWarnings就能解决问题:

suppressWarnings(withCallingHandlers(expr = fn1(),
                    warning = function(w) {
                        message(paste0("saved to a file: ", w$message))
                        # write(w$message, "xxlocation")
                    },
                    finally = function(x) suppressWarnings(x)
))

saved to a file: this is a warning!
[1] 1

关于r - 在R中带有警告的函数中抑制,记录和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62055311/

相关文章:

java - 在 try catch block java 中获取未处理的异常

当 R 中所有行的一列不同时,删除除一个重复行以外的所有行

forms - 手动设置Flutter验证错误

django - 使用(contrib.auth.models用户)的用户注册页面,但面临“非空约束错误”

C# Try-catch 不捕获异常

java - 带返回值的 Try/Catch 循环

r - 没有省略值的分组非密集排名

r - group by 之后加入 data.table

r - : operator 的不一致行为

mongodb - 您如何提取MongoError : E11000 duplicate key found?的错误消息