问题
Answer to question about error handling with lapply always return NA
or NULL
when an element fails, i.e.
myfun <- function(s) {
tryCatch(doSomething(s), error = function(e) { return(NULL) }
}
However, this is not general enough since doSomething(s)
may return NULL
or NA
itself. Therefore, ideally I want myfun
written so that after lapply(mylist, myfun)
I can somehow get all the indices of failed elements. How to do this?
回答1:
Catch and release the error by handing it with identity()
res = lapply(list(1, "two", 3), function(i) tryCatch({
sqrt(i)
}, error=identity)
Check for errors
vapply(res, is, logical(1), "error")
Returning the error condition is often better the returning a 'magic' value like NA
or NULL
, unless the down-stream analysis works seamlessly with the value returned.
As a more advanced solution, create a more elaborate condition or extend the error class
my_condition = function(err)
structure(list(message=conditionMessage(err),
original=err), class=c("my", "condition"))
and return that
res <- lapply(list(1, "two", 3), function(i) {
tryCatch({
sqrt(i)
}, error=my_condition)
})
来源:https://stackoverflow.com/questions/34908018/error-handling-with-lapply-output-the-index-of-failed-elements