使用 lapply 进行错误处理——输出失败元素的索引

Error handling with lapply -- output the index of failed elements

Answer to question about error handling with lapply 始终 return NANULL 当元素失败时,即

myfun <- function(s) {
  tryCatch(doSomething(s), error = function(e) { return(NULL) }
}

然而,这还不够普遍,因为 doSomething(s) 可能 return NULLNA 本身。因此,理想情况下我想写 myfun 以便在 lapply(mylist, myfun) 之后我可以以某种方式获得失败元素的所有索引。如何做到这一点?

通过 identity()

传递错误来捕获并释放错误
res = lapply(list(1, "two", 3), function(i) tryCatch({
    sqrt(i)
}, error=identity)

检查错误

vapply(res, is, logical(1), "error")

返回错误条件通常比 returning 'magic' 值(如 NANULL 更好,除非 down-stream 分析与值 returned.

作为更高级的解决方案,创建更详细的条件或扩展错误 class

my_condition = function(err)
    structure(list(message=conditionMessage(err),
                   original=err), class=c("my", "condition"))

和return那

res <- lapply(list(1, "two", 3), function(i) {
    tryCatch({
        sqrt(i)
    }, error=my_condition)
})