purrr (version 0.2.2.2)

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. This allows you to create very compact anonymous functions with up to two inputs.

If character or integer vector, e.g. "y", it is converted to an extractor function, function(x) x[["y"]]. To index deeply into a nested list, use multiple values; c("x", "y") is equivalent to z[["x"]][["y"]]. You can also set .null to set a default to use instead of NULL for absent components.

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
# NOT RUN {
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