purrr (version 0.2.5)

safely: Capture side effects.


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


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


possibly(.f, otherwise, quiet = TRUE)




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. There are three ways to refer to the arguments:

  • For a single argument function, use .

  • For a two argument function, use .x and .y

  • For more arguments, use ..1, ..2, ..3 etc

This syntax allows you to create very compact anonymous functions.

If character vector, numeric vector, or list, it is converted to an extractor function. Character vectors index by name and numeric vectors index by position; use a list to index by position and name at different levels. Within a list, wrap strings in get-attr() to extract named attributes. If a component is not present, the value of .default will be returned.


Default value to use when an error occurs.


Hide errors (TRUE, the default), or display them as they occur?


safely: wrapped function instead returns a list with components result and error. One value is always NULL.

quietly: wrapped function instead returns a list with components result, output, messages and warnings.

possibly: wrapped function uses a default value (otherwise) whenever an error occurs.


Run this code
safe_log <- safely(log)

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

# 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() %>%

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

# For interactive usage, auto_browse() is useful because it automatically
# starts a browser() in the right place.
f <- function(x) {
  y <- 20
  if (x > 5) {
  } else {
if (interactive()) {
  map(1:6, auto_browse(f))

# It doesn't make sense to use auto_browse with primitive functions,
# because they are implemented in C so there's no useful environment
# for you to interact with.
# }

Run the code above in your browser using DataCamp Workspace