16

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?

Hugh
  • 15,521
  • 12
  • 57
  • 100
  • I have yet to see this implemented, but I would love to be proven wrong. – Roman Luštrik Jul 27 '16 at 04:43
  • Does `options("warning.expression")` provide a clue? I can only use it to remove all warning messages entirely. – Hugh Jul 27 '16 at 04:47
  • That option is there for replacing warning messages with something more custom made. R's capturing of messages isn't its strong suit (I'm thinking a comparison to Python right now), but is good enough for stats. :) – Roman Luštrik Jul 27 '16 at 04:50
  • Dunno how ugly you want your code to be, but you could redefine the function as the function wrapped in suppressWarnings, conceivably. (I never use warnings or ggplot2, so I might be way off.) – Frank Jul 27 '16 at 04:58

1 Answers1

13

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.

Community
  • 1
  • 1
Martin Morgan
  • 45,935
  • 7
  • 84
  • 112