Skip to content

Instantly share code, notes, and snippets.

@TimTaylor
Created November 5, 2020 11:26
Show Gist options
  • Save TimTaylor/c856b327ae13aa07b82c3853d2503123 to your computer and use it in GitHub Desktop.
Save TimTaylor/c856b327ae13aa07b82c3853d2503123 to your computer and use it in GitHub Desktop.
Examples of safely function
# safe wrapper for functions ---------------------------------------------------
safely <- function(fun) {
function(...) {
warn <- err <- NULL
res <- withCallingHandlers(
tryCatch(fun(...), error = function(e) {
err <<- conditionMessage(e)
NULL
}),
warning = function(w) {
warn <<- append(warn, conditionMessage(w))
invokeRestart("muffleWarning")
}
)
list(res = res, warn = warn, err = err)
}
}
# Individual examples ----------------------------------------------------------
# generate data and make safe functions
dat <- data.frame(x = 1:10, y = 1:10)
safe_glm <- safely(glm)
safe_glm_nb <- safely(MASS::glm.nb)
message("example 1 - no warnings or errors")
safe_glm(y ~ x, data = dat, family = "poisson")
message("example 2 - errors")
safe_glm(y ~ x, family = "poisson")
message("example 3 - warnings")
safe_glm_nb(y ~ x, data = dat)
# List example -----------------------------------------------------------------
# generate data and make safe function
funky <- function(x = "ok") {
switch(
x,
ok = "Everything is good in the world",
warning = {
warning("1st warning")
warning("2nd warning")
"you still get a result but we capture all warnings"
},
stop("Aaaarrrghhh!!!!!!!!")
)
}
safe_funky <- safely(funky)
dat <- c("ok", "warning", "chaos")
message("list example")
lapply(dat, safe_funky)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment