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.
x <<-
, but that doesn't work.suppressWarnings(x <- sqrt(-1))
I do not know how to recover the warning message.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
: