Learn R Programming

purrr (version 0.2.1)

safely: Capture side effects.

Description

These functions wrap functions so instead generating side effects through output, messages, warnings, and errors, they instead return enchanced output. They are all adverbs because they modify the action of a verb (a function).

Usage

safely(.f, otherwise = NULL, quiet = TRUE)

quietly(.f)

possibly(.f, otherwise, quiet = TRUE)

Arguments

.f
A function, formula, or atomic vector.

If a function, it is used as is.

If a formula, e.g. ~ .x + 2, it is converted to a function with two arguments, .x or . and .y

otherwise
Default value to use when an error occurs.
quiet
Hide errors (TRUE, the default), or display them as they occur?

Value

  • safe: a list with components result and error. One value is always NULL

    outputs: a list with components result, output, messages and warnings.

Examples

Run this code
safe_log <- safely(log)
safe_log(10)
safe_log("a")

list("a", 10, 100) %>%
  map(safe_log) %>%
  transpose()

# This is a bit easier to work with if you supply a default value
# of the same type and use the simplify argument to transpose():
safe_log <- safely(log, otherwise = NA_real_)
list("a", 10, 100) %>%
  map(safe_log) %>%
  transpose() %>%
  simplify_all()

# To replace errors with a default value, use possibly().
list("a", 10, 100) %>%
  map_dbl(possibly(log, NA_real_))

Run the code above in your browser using DataLab