Created
August 22, 2019 14:51
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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