Created
August 30, 2017 12:56
-
-
Save dsparks/61428941c521f31439b7483a957e4063 to your computer and use it in GitHub Desktop.
A function that sometimes fails, and a wrapper for that function that runs the first one until it does not fail
This file contains 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
my_function <- function(x){ # This is a function that sometimes fails | |
doesItWork <- rnorm(1) > x | |
if(doesItWork){ | |
return("You got a result") | |
} else { | |
stop("Did not work") | |
} | |
} | |
function_wrapper <- function(y){ # This function tries the first one until it works | |
finallyWorked <- FALSE | |
while(!finallyWorked){ | |
resultObject <- try(my_function(y)) | |
if(class(resultObject) != "try-error"){ | |
finallyWorked <- TRUE | |
} | |
} | |
return(resultObject) | |
} | |
function_wrapper(0.5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I believe it is possible for the class of a failed
try
to be more complex than just"try-error"
. You might want to use!"try-error" %in% class(resultObject)
instead.