[R] recovering from errors with lapply()

Milan Bouchet-Valat nalimilan at club.fr
Wed Feb 13 10:51:15 CET 2013


Le mardi 12 février 2013 à 15:41 -0600, Andrew Barr a écrit :
> 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
The problem happens before lapply() itself:
> c(10,"This is not a number")
[1] "10"  "This is not a number"

A vector can only contain values of the same type, so 10 is converted to
a character value, and divideBy2("10") does not work. Try with:
lapply(list(10, "This is not a number"), divideBy2)

All that means that in real use cases, your tryCatch() solution should
work (I have not tested it). The bug is in your toy example.


Regards

> #[[1]]
> #[1] 5
> #[[2]]
> #[1] "An Error Occurred"
> 
> Thanks very much for your time.
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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.



More information about the R-help mailing list