[R] How to a handle an error in a loop

Seth Falcon sfalcon at fhcrc.org
Sun May 7 03:30:22 CEST 2006


"Farrel Buchinsky" <fjbuch at gmail.com> writes:
> No heaven on earth yet.
>
> how would I incorporate this kind of functionality into
> Resultdt<-lapply(PGWide[,240:389], tdt)

If you want to do more than one thing, you want to create an anonymous
function.  Here's an example:

    d <- runif(20, min=-2, max=8) # test data
    
    aFunc <- function(x) {  # gives error occasionally
        if (x > 0)
          x
        else
          stop("encountered bad x")
    }
    
    result <- lapply(d, function(z) {
        ans <- tryCatch(aFunc(z),
                        error=function(e) NULL)
        ans
    })
    
    result <- result[!sapply(result, is.null)]


Along these lines, here's a helper function that behaves similarly to
lapply, but by default _ignores errors_ and returns a vector of _only_
the "good" values.

        WARNING: lightly tested, may not be useful, doesn't behave
        exactly like lapply, money back only if unopened.

collect <- function(x, FUN, skip_error=TRUE, args_list=NULL)
{
    if (!is.vector(x))
      stop("arg x must be a vector")
    fname <- deparse(substitute(FUN))
    xvar <- deparse(substitute(x))
    i <- 1
    j <- 1
    result <- vector(mode=mode(x), length=length(x))
    while (i <= length(x)) {
        tryCatch({
            args <- list(x[i])
            if (length(args_list))
              args <- c(args, args_list)
            ans <- do.call(FUN, args)
            result[j] <- ans
            j <- j + 1
        }, error=function(e) {
            if (!skip_error) {
                msg <- paste("collect\n",
                             "call to", fname, "failed at", 
                             paste(xvar, "[",  i, "]\n", sep=""),
                             "Message:\n", conditionMessage(e))
                stop(msg, call.=FALSE)
            }
            NULL
        },
                 finally={i <- i + 1})
    }
    if (j > 1)
      result[1:(j-1)]
    else
      vector(mode=mode(x), length=0)
}

## Example

collect(d, aFunc, skip_error=FALSE)
Error: collect
 call to aFunc failed at d[2]
 Message:
 encountered bad x

collect(d, aFunc, skip_error=TRUE)
 [1] 7.7380303 0.7554328 1.8352623 0.5136118 4.4231091 2.5368103 1.8656615
 [8] 2.9244200 2.1364120 7.6711189 0.2141325 7.8216620 5.8347576 5.3939892


Cheers,

+ seth




More information about the R-help mailing list