Nicktz
3/3/2016 - 12:28 PM

Specific warning suppression

Adjusting the documentation of ?suppressWarning to only suppress a very specific warning, e.g. if we know a function will warn about zero standard deviation:

foo <- function() {
x <- cor( c(1,1,1,1,1),c(1:5),method = 'spearman',use = "pairwise.complete.obs")
}

x <- foo() # This produces the warning: "the standard deviation is zero"

To suppress this warning when running foo(), wrap it with the following function:

  suppressSpecificWarning <- function(expr, messages = character())
  {
    opts <- options(warn = -1)
    on.exit(options(opts))
    withCallingHandlers(expr, warning=function(w) {
      if (conditionMessage(w) %in% messages)
        invokeRestart("muffleWarning")
    })
  }


x <- suppressSpecificWarning( foo(), messages = "the standard deviation is zero") # No warning
x <- foo() # Warning