gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 08:40:25 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com