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

问题描述 投票:0回答:1

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

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个回答
0
投票

事实证明,解决方案很简单,只需在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
© www.soinside.com 2019 - 2024. All rights reserved.