通过正则表达式过滤的选择性抑制警告() [英] Selective suppressWarnings() that filters by regular expression
问题描述
为了生成运行时没有警告并因此可以使用 options(warn=2)
运行的代码,我正在寻找 suppressWarnings
例程的实现这只会过滤与给定(向量)正则表达式匹配的警告.有些警告是我无法控制的,比如著名的
In an attempt to generate code that runs without warnings and hence can be run with options(warn=2)
, I am looking for an implementation of the suppressWarnings
routine that would only filter warnings that match a given (vector of) regular expressions. Some warnings are just beyond my control, like the famous
Unrecognized record type 7, subtype 18 encountered in system file
在读取某些 SPSS 文件时,我想有选择地抑制这些文件而不影响可能的其他警告.
when reading certain SPSS files, and I want to selectively suppress these without affecting possible other warnings.
是否已经实现了此功能?
Is there already an implementation of this functionality?
推荐答案
使用 中提到的muffleWarning"重启,使用
withCallingHandlers
和 invokeRestart
抑制警告?警告
Suppress warnings with withCallingHandlers
and invokeRestart
, using the "muffleWarning" restart mentioned on ?warning
withCallingHandlers({
x <- 0
warning("Unrecognized record 123")
x <- x + 1
warning("another warning")
x + 1
}, warning = function(w) {
if (startsWith(conditionMessage(w), "Unrecognized record"))
invokeRestart("muffleWarning")
})
这里有输出
[1] 2
Warning message:
In withCallingHandlers({ : another warning
(如果您想在警告时停止,请使用 tryCatch
).正如@BenBolker 提到的,这不处理翻译;制作更精细的正则表达式不会令人满意.为了捕捉自己的警告,可以制作和抛出警告的子类.
(use tryCatch
if instead you would like to stop on warning). As @BenBolker mentions this doesn't handle translations; making a more elaborate regex isn't going to be satisfactory. For catching one's own warnings, one could make and throw a subclass of warning.
这篇关于通过正则表达式过滤的选择性抑制警告()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!