An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20130212/def541bf/attachment.pl>
recovering from errors with lapply()
3 messages · Andrew Barr, Milan Bouchet-Valat
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.
An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20130213/0f05a4b6/attachment.pl>