How can I execute a statement and ignore warnings with tryCatch?

34 views Asked by At

I tried the following code:

x <- NULL
tryCatch(
  x <- sqrt(-1),
  warning = function(cond) print(paste("Ignore: ", conditionMessage(cond)))
)
# [1] "Ignore:  NaNs produced"

Expected output:

# [1] "Ignore:  NaNs produced"
x
#NaN

Notice that x is still NULL. No value has been assigned.

  • I tried x <<-, but that doesn't work.
  • I would like to show the ignored warning, instead of just suppressing the warnings. After suppressWarnings(x <- sqrt(-1)) I do not know how to recover the warning message.
1

There are 1 answers

0
r2evans On BEST ANSWER

When you tryCatch(.., warning=), the first time the warning happens, the expression is interrupted and control is never returned to it. In order to "ignore" warnings, you need withCallingHandlers and invokeRestart("mufflewarning").

withCallingHandlers(
  x <- sqrt(-1),
  warning = function(w) invokeRestart("muffleWarning"))
x
# [1] NaN

One good reference for studying error/warning conditions is https://adv-r.hadley.nz/conditions.html.

I think there are two times when it makes sense to me to use "muffleWarning" instead of suppressWarnings:

  • when I want to suppress specific warnings only, and allow all others to emit; this is by far the majority use-case for me; and
  • when you want to change something because of a warning; I don't have a clear example of what to use this, as it is 100% contextual.