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.For those who do not need a full try-catch-handler but who only want to briefly "pass" execution of a single line of code in case of an error (and continue execution of the rest of code). One can use:
suppressWarnings(try(...))
try()
also has the argument silent
which allows to "shut up" R not only in case of a warning, but also in case of an error.
suppressWarnings(try(warning("Warning here")))
...returns no information regarding the warning.
suppressWarnings(try(stop("Errro here"), silent=TRUE))
...returns no information regarding the error.
Example:
for (x in seq(1,10)){
print(x)
if (x == 5){try(stop("Error here..."))}
}