Skip to content

Instantly share code, notes, and snippets.

@dsparks
Created August 30, 2017 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsparks/61428941c521f31439b7483a957e4063 to your computer and use it in GitHub Desktop.
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
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)
@briatte
Copy link

briatte commented Aug 30, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment