🎓 A1Learner
🔍
0 of 27 lessons completed

R Muffling Warnings

Muffling a warning drops its message while the code around it carries on. withCallingHandlers() runs a block of code with a handler that steps in when a warning fires.

A warning on its own

The block holds a single warning call and prints nothing. The whole stated output is the warning block from the error stream.

warning("careful now")

Muffle the warning

The handler calls invokeRestart with the muffleWarning restart. The warning never prints and the cat line after it still runs.

withCallingHandlers({
  warning("careful now")
  cat("still running\n")
}, warning = function(w) {
  invokeRestart("muffleWarning")
})

The handler runs first

This handler prints its own line before it muffles the warning. The handler line comes first in the output, which shows the handler ran while the block was still going.

withCallingHandlers({
  warning("careful now")
  cat("still running\n")
}, warning = function(w) {
  cat("handler saw the warning\n")
  invokeRestart("muffleWarning")
})

Catch a warning as a value

tryCatch treats the warning as a catchable condition. The handler returns the message text, and that text becomes the value of the call.

caught <- tryCatch(warning("careful now"), warning = function(w) {
  conditionMessage(w)
})
print(caught)

Example

check <- function(balance) {
  withCallingHandlers({
    if (balance < 10) {
      warning("balance is low")
    }
    cat("balance checked\n")
  }, warning = function(w) {
    invokeRestart("muffleWarning")
  })
  cat("check finished\n")
}
check(5)
check(50)

Key points

  • A warning prints its message on the error stream and the script keeps going.
  • withCallingHandlers() takes the code to run first and handler functions after it.
  • A warning handler runs at the moment the warning fires, while the block is still running.
  • invokeRestart("muffleWarning") inside the handler drops the warning and lets the block continue.
  • The lines after a muffled warning still run.
  • tryCatch() can catch a warning too, and the handler value then becomes the result of the call.

In this example, check warns when the balance is below 10 and the handler muffles that warning. Both calls print the same two lines, so the low balance call carries on exactly like the healthy one.

Try it Yourself

Edit the code, then press Run.

Running is simulated · rdrr.io R Snippets

Exercise

What happens to the lines after a warning when a handler calls invokeRestart("muffleWarning")?