6

为了生成在没有警告的情况下运行并因此可以运行的代码options(warn=2),我正在寻找一个suppressWarnings例程的实现,它只过滤与给定正则表达式(向量)匹配的警告。有些警告超出了我的控制范围,比如著名的

Unrecognized record type 7, subtype 18 encountered in system file

在读取某些 SPSS 文件时,我想有选择地抑制这些文件而不影响可能的其他警告。

是否已经实现了此功能?

4

2 回答 2

9

withCallingHandlers使用和抑制警告invokeRestart,使用上面提到的“muffleWarning”重启?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 提到的,这不处理翻译;制作更精细的正则表达式不会令人满意。为了捕捉自己的警告,可以制作并抛出警告的子类

于 2013-05-13T11:34:47.897 回答
3

为方便起见,我围绕@martin-morgan 的答案编写了一个包装器,它的工作原理类似于SuppressWarnings您可以使用点将正则表达式传递给第二个参数(将传递给grepl)或将应用于错误消息的函数作为附加论据。

我让它支持公式表示法。

请参阅下面的示例。

suppress_warnings <- function(.expr, .f, ...) {
  eval.parent(substitute(
  withCallingHandlers( .expr, warning = function(w) {
    cm <- conditionMessage(w)
    cond <- 
      if(is.character(.f)) grepl(.f, cm) else rlang::as_function(.f)(cm,...)
    if (cond) {
      invokeRestart("muffleWarning")
    }
  })
  ))
}


suppress_warnings({sqrt(-1); warning("ooops", call. = FALSE)}, startsWith, "o")
# Warning message:
# In sqrt(-1) : NaNs produced
suppress_warnings({sqrt(-1); warning("ooops", call. = FALSE)}, ~nchar(.)>10)
# Warning message:
# ooops
suppress_warnings({sqrt(-1); warning("ooops", call. = FALSE)}, "NaN")
# Warning message:
# ooops
于 2019-03-15T12:16:27.753 回答