禁止发出特定警告消息

Hug*_*ugh 4 warnings r

我有一个源文件(在knitr中),其中包含使用特定字体系列的图形。我想禁止显示警告消息

在grid.Call(L_textBounds,as.graphicsAnnot(x $ label),...:Windows字体数据库中找不到字体系列

library(ggplot2)

ggplot(mtcars, aes(mpg, cyl, label = gear)) + 
  geom_text(family = "helvet")
Run Code Online (Sandbox Code Playgroud)

我知道我可以禁止脚本中的所有警告消息options(warn = -1),并且知道如何使用suppressWarnings。我也可以在中包围一个特定的块tryCatch

有没有办法只禁止整个文件中的grid.Call上述警告?

Mar*_*gan 7

使用

withCallingHandlers({
    <your code>
}, warning=function(w) {
    if (<your warning>)
        invokeRestart("muffleWarning")
})
Run Code Online (Sandbox Code Playgroud)

例如,

x = 1
withCallingHandlers({
    warning("oops")
    warning("my oops ", x)
    x
}, warning=function(w) {
    if (startsWith(conditionMessage(w), "my oops"))
        invokeRestart("muffleWarning")
})
Run Code Online (Sandbox Code Playgroud)

产生输出

[1] 1
Warning message:
In withCallingHandlers({ : oops
>
Run Code Online (Sandbox Code Playgroud)

局限性是可以将conditionMessage转换为另一种语言(尤其是从基本函数转换时),从而无法可靠地标识文本。

请参阅按正则表达式过滤的Selective preventWarnings()