使用lapply进行错误处理-输出失败元素的索引 [英] Error handling with lapply -- output the index of failed elements
问题描述
对使用lapply处理错误的疑问总是返回 NA
或 NULL
,当元素失败时,即
myfun<-函数{tryCatch(doSomething(s),错误=函数(e){return(NULL)}}
但是,这还不够通用,因为 doSomething(s)
可能会返回 NULL
或 NA
本身.因此,理想情况下,我希望编写 myfun
,以便在 lapply(mylist,myfun)
之后,我能够以某种方式获取所有失败元素的索引.该怎么做?
使用 identity()
res = lapply(list(1,"two",3),function(i)tryCatch({sqrt(i)},错误=身份)
检查错误
vapply(res,是,逻辑(1),错误")
返回错误条件通常比返回'magic'值(例如 NA
或 NULL
)更好,除非下游分析与返回的值无缝地配合./p>
作为更高级的解决方案,请创建更复杂的条件或扩展错误类别
my_condition = function(err)结构(列表(消息= conditionMessage(err),original = err),class = c("my","condition"))
并退回
res<-lapply(list(1,"two",3),function(i){试着抓({sqrt(i)},错误= my_condition)})
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?
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)
})
这篇关于使用lapply进行错误处理-输出失败元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!