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

时间:2016-01-20 18:45:53

标签: r error-handling lapply

当元素失败时,

Answer to question about error handling with lapply始终返回public class ProtocolsLayer : Layer { private IFrameworkDependencyResolver _resolver; private IConfigurationService _configService; public ProtocolsLayer(IFrameworkDependencyResolver resolver, IConfigurationService configurationService) { _resolver = resolver; _configService = configurationService; } void HandleConnection1() { // What I have at the moment (terrible): // Resolve the fitting services (All keyed - key is received by the type, Resolve and ResolveWithParameters used here are my wrappers) var agent = _resolver.Resolve<IFramingAgent>(typeof(Protocol1FramingAgent)); var algo = _resolver.Resolve<IFramingAlgorithm>(typeof(Protocol1FramingAlgorith)); var parser = _resolver.Resolve<IFramingParser>(typeof(Protocol1FramingParser)); // A parameter I get and pass to each protocol at runtime var protocolConfig = _configService.GetConfig<Protocol1Configuration>(); // Finally resolve the protocol with it's parameters: protocol = _resolver.ResolveWithParameters<IProtocol>(typeof(Protocol1), new List<object>{ agent, resolver, parser, protocolConfig }); //... // Theres gotta be a better way!! } void HandleConntection2() { // Same as in protocol1 } void HandleConnection3() { // Same as in protocol1 } } NA,即

NULL

但是,这不够通用,因为myfun <- function(s) { tryCatch(doSomething(s), error = function(e) { return(NULL) } } 可能会返回doSomething(s)NULL本身。因此,理想情况下我希望NA编写,以便在myfun之后,我可以以某种方式获取失败元素的所有索引。怎么做?

1 个答案:

答案 0 :(得分:2)

通过使用identity()

处理错误来捕获并解除错误
res = lapply(list(1, "two", 3), function(i) tryCatch({
    sqrt(i)
}, error=identity)

检查错误

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

返回错误条件通常会更好地返回“{magic”值,例如NANULL,除非下游分析与返回的值无缝协作。

作为更高级的解决方案,创建更复杂的条件或扩展错误类

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

并返回

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