Skip to content

avoid error within for loop, try, trycatch, while, move to next iteration, unlist

3 messages · Λεωνίδας Μπαντής, William Dunlap

#
You could put the try() into a while loop, inside for for or lapply loop,
as in:
[1] 0.5000588 0.9991261

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
You could encapsulate this idiom in a function:

untilOK <- function (expr, silent = TRUE, maxIter = 1000,
    quotedExpr = substitute(expr),  envir = parent.frame()) 
{
    while ((maxIter <- maxIter - 1) >= 0 && inherits(tmp <- try(eval(quotedExpr, 
        envir = envir), silent = silent), "try-error")) {
    }
    if (maxIter < 0) {
        stop("reached maxIter iterations, last error message is ", 
            as.character(tmp))
    }
    tmp
}

E.g.,

  > f <- function(x){ stopifnot(x>0.9) ; x } # fails 90% of time
  > vapply(1:10, function(i)untilOK(f(runif(1))), FUN.VALUE=0.0)
   [1] 0.9460461 0.9670447 0.9306208 0.9122009 0.9495725 0.9619204 0.9031418 0.9624259 0.9809273 0.9518705
  > untilOK(stopifnot(1==2)) # maxIter=1000 protects against inappropriate expressions.
  Error in untilOK(stopifnot(1 == 2)) : 
    reached maxIter iterations, last error message is Error : 1 == 2 is not TRUE

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com