在特定情况下将函数转换为具有错误处理的函数

时间:2019-04-18 11:59:57

标签: r function error-handling

我想对这个问题的接受答案使用函数:

How do I save warnings and errors as output from a function?

factory <- function(fun)
    function(...) {
        warn <- err <- NULL
        res <- withCallingHandlers(
            tryCatch(fun(...), error=function(e) {
                err <<- conditionMessage(e)
                NULL
            }), warning=function(w) {
                warn <<- append(warn, conditionMessage(w))
                invokeRestart("muffleWarning")
            })
        list(res, warn=warn, err=err)
    }

用于以下功能:

rbindlistfun <- function(df1, df2) {
x <- rbindlist(list(df1, df2), fill=TRUE, use.names=TRUE)
return (x)
}

OP的答案给出以下示例:

test <- function(i)
    switch(i, "1"=stop("oops"), "2"={ warning("hmm"); i }, i)
res <- lapply(1:3, factory(test))

但是我不完全了解这与我的功能之间的关系。如何在示例中使用工厂功能?

0 个答案:

没有答案