safely {purrr} | R Documentation |
Wrap a function to capture errors
Description
Creates a modified version of .f
that always succeeds. It returns a list
with components result
and error
. If the function succeeds, result
contains the returned value and error
is NULL
. If an error occurred,
error
is an error
object and result
is either NULL
or otherwise
.
Usage
safely(.f, otherwise = NULL, quiet = TRUE)
Arguments
.f |
A function to modify, specified in one of the following ways:
|
otherwise |
Default value to use when an error occurs. |
quiet |
Hide errors ( |
Value
A function that takes the same arguments as .f
, but returns
a different value, as described above.
Adverbs
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()
,
possibly()
,
quietly()
,
slowly()
Examples
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()