possibly: Wrap a function to return a value instead of an error

View source: R/adverb-possibly.R

possiblyR Documentation

Wrap a function to return a value instead of an error


Create a modified version of .f that return a default value (otherwise) whenever an error occurs.


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



A function to modify, specified in one of the following ways:

  • A named function, e.g. mean.

  • An anonymous function, e.g. ⁠\(x) x + 1⁠ or function(x) x + 1.

  • A formula, e.g. ~ .x + 1. Only recommended if you require backward compatibility with older versions of R.


Default value to use when an error occurs.


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


A function that takes the same arguments as .f, but returns a different value, as described above.


This function is called an adverb because it modifies the effect of a function (a verb). If you'd like to include a function created an adverb in a package, be sure to read faq-adverbs-export.

See Also

Other adverbs: auto_browse(), compose(), insistently(), negate(), partial(), quietly(), safely(), slowly()


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

# The default, NULL, will be discarded with `list_c()`
list("a", 10, 100) |>
  map(possibly(log)) |>

purrr documentation built on Aug. 10, 2023, 9:08 a.m.