在 R 中使用 tryCatch 抑制警告 [英] Suppress warnings using tryCatch in R
问题描述
编写一个 tryCatch
来处理错误值但忽略警告.举个例子
Write a tryCatch
that will handle an error value but will ignore a warning. As an example
foo <- function(x) {
if (x == 1) {
warning('Warning')
} else if (x == 0) {
stop('Error')
}
return(1)
}
bar <- function(x){
tryCatch(
expr = foo(x),
error = identity,
warning = function(w) invokeRestart("muffleWarning")
)
}
所以 foo
会在传递 0 时警告您,传递 1 时会出错. bar
的目的是传递 0 时会出现错误,但它会抑制 bar
生成的警告,如果你传递一个 1. invokeRestart("muffleWarning")
命令来自 suppressWarnings
的定义.它在我这里的建筑中不起作用,我不知道为什么.(具有讽刺意味的是,它会生成一个错误,因此尝试成功将我不想要的警告升级为我无法解释的错误.)
So foo
warns you if you pass a 0, and errors if you pass a 1. The intent of bar
is that you get an error if you pass a 0, but it suppresses the warning generated by bar
if you pass a 1. The invokeRestart("muffleWarning")
command comes from the definition of suppressWarnings
. It does not work in the construction I have here and I do not know why. (Ironically it generates an error, so trying that successfully escalated a warning I didn't want into an error that I can't interpret.)
bar
的这个定义会起作用
bar <- function(x){
tryCatch(
expr = foo(x),
error = SomeFunctionThatDoesNotMatter,
warning = function(w){suppressWarnings(foo(x))}
)
}
bar
完全符合我的要求,但它以一种可能很糟糕的方式做到了.想象一下,我有 expr = lapply(X=1:50, ...)
而不是 expr = foo(x)
并且 expr = lapply(X=1:50, ...)
code>FUN 需要一个小时才能运行.如果 X[50]
生成唯一的警告,那么我的运行时间会从 50 小时增加一倍到 100 小时(糟糕).
bar
does exactly what I want it to, but it does it in a potentially terrible way. Imagine that instead of expr = foo(x)
as I have here, that I have expr = lapply(X=1:50, ...)
and that the FUN
takes an hour to run. If X[50]
generates the only warning then my run time has double from 50 hours to 100 hours (yuck).
- 为什么
invokeRestart("muffleWarning")
在我上面的例子中不起作用? - 在使用
tryCatch
时,应该为warning
分配什么功能,以便让代码继续运行并抑制生成的警告?
- Why does
invokeRestart("muffleWarning")
not work in my example above? - When using
tryCatch
, what function should be assigned towarning
in order to allow the code to simply keep running and suppress the warnings that are generated?
感谢阅读!
推荐答案
在遵循 nrussell 的直觉之后,我遇到了这个问题.解决办法是替换通用的
I ran into this problem after following nrussell's intuition. The solution is to replace the generic
tryCatch({
some_fn()
}, warning = function(w) {
print(paste('warning:', w))
}, error = function(e) {
print(paste('error:', e))
})
与
tryCatch({
some_fn()
}, error = function(e) {
print(paste('error:', e))
})
这种格式/语法对我有用.您可以轻松地将其包含在您需要的函数中
This format/syntax has worked for me. You could easily enclose it in a function like you need to
这篇关于在 R 中使用 tryCatch 抑制警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!