safely {purrr} | R Documentation |
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).
safely(.f, otherwise = NULL, quiet = TRUE) quietly(.f) possibly(.f, otherwise, quiet = TRUE)
.f |
A function, formula, or atomic vector. If a function, it is used as is. If a formula, e.g. If character or integer vector, e.g. |
otherwise |
Default value to use when an error occurs. |
quiet |
Hide errors ( |
safe
: a list with components result
and error
.
One value is always NULL
outputs
: a list with components result
, output
,
messages
and warnings
.
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_))