8.3 Ignoring conditions

The simplest way of handling conditions in R is to simply ignore them:

  • Ignore errors with try().
  • Ignore warnings with suppressWarnings().
  • Ignore messages with suppressMessages().

These functions are heavy handed as you can’t use them to suppress a single type of condition that you know about, while allowing everything else to pass through. We’ll come back to that challenge later in the chapter.

try() allows execution to continue even after an error has occurred. Normally if you run a function that throws an error, it terminates immediately and doesn’t return a value:

f1 <- function(x) {
  log(x)
  10
}
f1("x")
#> Error in log(x): non-numeric argument to mathematical function

However, if you wrap the statement that creates the error in try(), the error message will be displayed35 but execution will continue:

f2 <- function(x) {
  try(log(x))
  10
}
f2("a")
#> Error in log(x) : non-numeric argument to mathematical function
#> [1] 10

It is possible, but not recommended, to save the result of try() and perform different actions based on whether or not the code succeeded or failed36. Instead, it is better to use tryCatch() or a higher-level helper; you’ll learn about those shortly.

A simple, but useful, pattern is to do assignment inside the call: this lets you define a default value to be used if the code does not succeed. This works because the argument is evaluated in the calling environment, not inside the function. (See Section 6.5.1 for more details.)

default <- NULL
try(default <- read.csv("possibly-bad-input.csv"), silent = TRUE)

suppressWarnings() and suppressMessages() suppress all warnings and messages. Unlike errors, messages and warnings don’t terminate execution, so there may be multiple warnings and messages signalled in a single block.

suppressWarnings({
  warning("Uhoh!")
  warning("Another warning")
  1
})
#> [1] 1

suppressMessages({
  message("Hello there")
  2
})
#> [1] 2

suppressWarnings({
  message("You can still see me")
  3
})
#> You can still see me
#> [1] 3

  1. You can suppress the message with try(..., silent = TRUE).↩︎

  2. You can tell if the expression failed because the result will have class try-error.↩︎