Skip to content

Instantly share code, notes, and snippets.

@benjaminguinaudeau
Created August 22, 2019 14:51
Show Gist options
  • Save benjaminguinaudeau/68ef279398bbf62baae9a6cce3b0551d to your computer and use it in GitHub Desktop.
Save benjaminguinaudeau/68ef279398bbf62baae9a6cce3b0551d to your computer and use it in GitHub Desktop.
This function does the same as try, but instead of trying only once, it will try the number of times specified by the parameter n.
try_n <- function(x, n = 2, .otherwise = "", quiet = T){
index <- 1
out <- try(1+a, silent = T)
while(index <= n & class(out) == "try-error"){
if(!quiet){message(glue::glue("Trial {index}"))}
out <- suppressWarnings(try(x, silent = T))
index <- index + 1
}
if(class(out) == "try-error"){
if(.otherwise == "") return(out) else return(.otherwise)
} else {
return(out)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment