Hi all,

I am searching for a way to recover results from lapply() when one or more
values returns an error.  I have a written a function that uses tryCatch()
to recover from errors. Here is a very simple example of such a function.

divideBy2<-function(X){
  result<-tryCatch(X/2, error = function(e) "An Error Occurred")
  return(result)
}

This function appears to work as I expect both in cases where an error
occurs and where no error occurs.

divideBy2(10)
# [1] 5

divideBy2("This is not a number")
# [1] "An Error Occurred"

I would like to use this function in an lapply(), but when I do so ALL of
the results returned are the results of an error.

lapply(c(10,"This is not a number"),FUN=divideBy2)

#[[1]]
#[1] "An Error Occurred"

#[[2]]
#[1] "An Error Occurred"

Is this how lapply() is meant to work? What I want is a list that looks
like this

#[[1]]
#[1] 5
#[[2]]
#[1] "An Error Occurred"

Thanks very much for your time.

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to