if (FALSE) {
fun <- function(warn1=FALSE, warn2=FALSE, warn3=FALSE, error=FALSE){
if(warn1) warning('Show this warning')
if(warn2) warning('Show a different warning')
if(warn3) warning('Last warning message')
if(error) stop('terminate function call')
return('Returned from fun()')
}
# normal run (no warnings or errors)
out <- fun()
out
# these are all the same
convertWarnings(out <- fun())
out <- convertWarnings(fun())
out <- fun() |> convertWarnings()
# errors treated normally
fun(error=TRUE)
fun(error=TRUE) |> convertWarnings()
# all warnings converted to errors
fun(warn1=TRUE)
fun(warn1=TRUE) |> convertWarnings()
fun(warn2=TRUE) |> convertWarnings()
# muffle all non-caught warnings (not recommended unless you know
# the R expression/function very intimately!)
retmuffle <- fun(warn1=TRUE) |>
convertWarnings('Warning not caught', muffle=TRUE)
retmuffle
# Specific warnings treated as errors (others stay as warnings)
# Here, treat first warning message as error but not the second or third
fun(warn1=TRUE) # warning
ret <- fun(warn1=TRUE) |> convertWarnings("Show this warning") # now error
fun(warn2=TRUE, warn3=TRUE) # warnings
ret23 <- fun(warn2=TRUE, warn3=TRUE) |> # continues, but prints warnings
convertWarnings("Show this warning")
ret23
# Explicitly convert multiple warning messages, allowing others through.
# This is generally the best use of the function's specificity
fun(warn1=TRUE, warn2=TRUE)
ret <- fun(warn1=TRUE) |> # error given either message
convertWarnings(c("Show this warning", "Show a different warning"))
ret <- fun(warn2=TRUE) |>
convertWarnings(c("Show this warning", "Show a different warning"))
# last warning gets through (left as valid warning), but message still raised
ret3 <- fun(warn3=TRUE) |>
convertWarnings(c("Show this warning", "Show a different warning"))
ret3
}
Run the code above in your browser using DataLab