collect_all: Collect warnings/errors/messages from an expression without...

View source: R/collect_all.R

collect_allR Documentation

Collect warnings/errors/messages from an expression without rerunning it

Description

collect_all wraps expressions and returns the result of the expression along with a list of warnings, errors, and messages raised by running the expression, without having to run the expression more than once.

Usage

collect_all(expr, catchErrors = FALSE, asStrings = TRUE)

Arguments

expr

The expression you want to catch warnings and messages for.

catchErrors

A boolean which, if true, will catch error messages just like it catches warnings and messages. It will then return NA as the value.

asStrings

A boolean which, if true, will convert the conditions into strings.

Details

I've personally found R's warning and message handling very confusing, and this represents "good enough" code for me. Using Aaron's answer to a question on stackexchange, I was able to understand enough of it to make a function that would collect all the warnings and messages raised by an expression and still run the code only once. (All other examples I encountered seemed to need to run the code twice to get both the result and the warnings.)
If, say, you're running a lot of models all at once, then having to rerun the code (as most tutorials/answers to warning handling with R suggest) would be a total pain in the butt.

Value

A named list with the result of the expression, the warnings, and the messages raised by the expression

Examples

# Let's say that `run_model_once(x)` fits a randomly generated glmer model with
#   a seed of `x`, as one might do in a power simulation
## Not run: results = data.frame(IterationNumber = seq(NUMBER_ITERATIONS))
results = results %>%
  dplyr::tbl_df() %>%
  dplyr::mutate(models = purrr::map(IterationNumber,
   ~zplyr::collect_all(run_model_once(.))))

## End(Not run)

burchill/zplyr documentation built on Feb. 2, 2023, 11:01 a.m.