Error handling with lapply — output the index of failed elements

烈酒焚心 提交于 2021-02-08 03:35:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!