Skip to content

Instantly share code, notes, and snippets.

@dsparks dsparks/try loop.R
Created Aug 30, 2017

What would you like to do?
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
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
resultObject <- try(my_function(y))
if(class(resultObject) != "try-error"){
finallyWorked <- TRUE

This comment has been minimized.

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
You can’t perform that action at this time.