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

From: Seth Falcon <sfalcon_at_fhcrc.org>
Date: Sun 07 May 2006 - 11:30:22 EST

"Farrel Buchinsky" <fjbuch@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



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Sun May 07 11:33:27 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Tue 09 May 2006 - 10:10:05 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.