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