【问题标题】:Suppress, log and return values in a function with warnings in R在 R 中带有警告的函数中抑制、记录和返回值
【发布时间】:2020-09-15 05:08:14
【问题描述】:

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

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

【问题讨论】:

    标签: r error-handling try-catch


    【解决方案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
    

    【讨论】:

    • 你不需要 finally 部分 suppressWarnings(withCallingHandlers(expr = fn1(), warning = function(w) { message(paste0("saved to a file: ", w$message)) })) 似乎工作相同。
    • 是的,对不起,忘记删除它。当我尝试不同的选项时会出现一些冗余代码。
    猜你喜欢
    • 2012-04-29
    • 2016-06-17
    • 1970-01-01
    • 2013-05-08
    • 2018-11-11
    • 2012-02-09
    • 1970-01-01
    • 2016-06-21
    相关资源
    最近更新 更多