try_fun {str2str}R Documentation

Add Try to Function

Description

try_fun creates a version of the function fun that evaluates the function and then returns a list with three elements: 1) return object, 2) warning message, 3) error message. This can be useful when you want to apply a function 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_fun(fun, output.class = paste0(deparse(substitute(fun)), ".try"))

Arguments

fun

function

output.class

character vector of length 1 specifying the class you want the result from a call to the returned function to be. Note, if fun is an annonymous function, then the default will probably not work due to the character limitations of deparsing a function. You can always put down NULL for no class, which will always work with annonymous functions.

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

function that returns a list object with three elements: "result" = 1) return object of fun, "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()
log.try <- try_fun(log)
log.try(1)
log.try(0)
log.try(-1)
log.try("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 <- log.try(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)
})

[Package str2str version 1.0.0 Index]