Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress any emission of a particular warning message

Tags:

r

warnings

I have a source file (in knitr) containing plots which use a particular font family. I'd like to suppress the warning messages

In grid.Call(L_textBounds, as.graphicsAnnot(x$label), ... : font family not found in Windows font database

library(ggplot2)

ggplot(mtcars, aes(mpg, cyl, label = gear)) + 
  geom_text(family = "helvet")

I know I can suppress all warning messages in a script options(warn = -1), and I know how to use suppressWarnings. I can also surround a particular chunk in a tryCatch.

Is there a way to suppress only the grid.Call warning above throughout a file?

like image 932
Hugh Avatar asked Jul 27 '16 04:07

Hugh


1 Answers

Use

withCallingHandlers({
    <your code>
}, warning=function(w) {
    if (<your warning>)
        invokeRestart("muffleWarning")
})

For instance,

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

produces output

[1] 1
Warning message:
In withCallingHandlers({ : oops
>

The limitation is that the conditionMessage may be translated to another language (especially if from a base function) so that the text will not be reliably identified.

See Selective suppressWarnings() that filters by regular expression.

like image 145
Martin Morgan Avatar answered Jan 04 '23 15:01

Martin Morgan