How to overwrite a warning in R

576 Views Asked by At

I have a function that generates an unwanted warning, but keeps the value.

f <- function(a) { 
  
  if (a > 1) { 
    warning("an uninformative warning")
  }
  a
}

g1 <- function(b) {
  
  withCallingHandlers(
    x <-f(b),
    warning = function(w) {
      warning("A more informative warning")
    })
  
  x
}
g1(2)
#> Warning in (function (w) : A more informative warning
#> Warning in f(b): an uninformative warning
#> [1] 2

Created on 2023-12-12 with reprex v2.0.2

Unfortunately, this thows 2 warnings.

With tryCatch() x is not kept. and with withCallingHandlers(), both warnings are thrown.

1

There are 1 best solutions below

8
Allan Cameron On BEST ANSWER

You can get your warning handler to emit its own warning, then invoke the muffleWarning restart:

f <- function(a) { 
  
  if (a > 1) { 
    warning("an uninformative warning")
  }
  a
}

g1 <- function(b) {
  
  withCallingHandlers(
    x <- f(b),
    warning = function(w) {
      warning('A more informative warning', call. = FALSE)
      tryInvokeRestart("muffleWarning")
    })
  x
}

Testing:

g1(2)
#> [1] 2
#> Warning message:
#> A more informative warning