try_expr {str2str} | R Documentation |
Add Try to Expression
Description
try_expr
evaluates an expression expr
and returns a list with three
elements: 1) return object, 2) warning message, 3) error message. This can be
useful when you want to evaluate an expression and are not sure if it will result
in a warning and/or error and don't want R to stop if an error does arise.
Usage
try_expr(expr, output.class = NULL)
Arguments
expr |
expression |
output.class |
character vector of length 1 specifying the class you want
the returned object of |
Details
This function is heavily based on the following StackOverflow post: https://stackoverflow.com/questions/4948361/how-do-i-save-warnings-and-errors-as-output-from-a-function.
Value
list object with three elements: "result" = 1) return object of expr
,
"warning" = warning message, "error" = error message. When an element is not
relevant (e.g., no errors), then that element is NULL.
Examples
# apply to log()
try_expr(log(1))
try_expr(log(0))
try_expr(log(-1))
try_expr(log("a"))
# return a list where NULL if an error or warning appears
lapply(X = list("positive" = 1, "zero" = 0, "negative" = -1,"letter" = "a"),
FUN = function(x) {
log_try <- try_expr(log(x))
result <- log_try[["result"]]
warning <- log_try[["warning"]]
error <- log_try[["error"]]
if (!(is.null(error))) return(NULL)
if (!(is.null(warning))) return(NULL)
return(result)
})