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.
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 needwithCallingHandlersandinvokeRestart("mufflewarning").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 ofsuppressWarnings: