8.3 Ignoring conditions

A few ways:

  • try()
  • suppressWarnings()
  • suppressMessages()

8.3.1 try()

What it does:

  • Displays error
  • But continues execution after error
bad_log <- function(x) {
  try(log(x))
  10
}

bad_log("bad")
#> Error in log(x) : non-numeric argument to mathematical function
#> [1] 10

Better ways to react to/recover from errors:

  1. Use tryCatch() to “catch” the error and perform a different action in the event of an error.
  2. Set a default value inside the call. See below.
default <- NULL
try(default <- read.csv("possibly-bad-input.csv"), silent = TRUE)
#> Warning in file(file, "rt"): cannot open file 'possibly-bad-input.csv': No such
#> file or directory

8.3.2 suppressWarnings(), suppressMessages()

What it does:

  • Supresses all warnings (messages)
# suppress warnings (from our `warn()` function above)
suppressWarnings(warn())

# suppress messages
many_messages <- function() {
  message("Message 1")
  message("Message 2")
  message("Message 3")
}

suppressMessages(many_messages())