R TryCatch 无法与 lapply 一起使用

4 r

我正在尝试将函数应用于文件列表lapply(我对数据框进行一些操作,然后编写绘图)。问题是,如果该函数引发文件错误

(无法对数据框进行计算)

,迭代停止。

我在函数中都使用了 tryCatch

ee = function(i){return(tryCatch(..., error=function(e) NULL))}
Run Code Online (Sandbox Code Playgroud)

并在lapply

lapply(list.files(path), tryCatch(ee, error=function(e) NULL)))
Run Code Online (Sandbox Code Playgroud)

但无论哪种情况,我都会继续检测到错误并停止迭代。任何想法?谢谢。

Rol*_*and 5

我相信你的第一个例子原则上应该有效,但不明白你用那里的省略号做什么。

这是一个简单的最小示例:

foo <- function(x) {
  if (x == 6) stop("no 6 for you")
  x
}

l <- list(1, 5, 6, 10)

lapply(l, foo)
# Error in FUN(X[[i]], ...) : no 6 for you 

bar <- function(x) tryCatch(foo(x), error = function(e) e)
lapply(l, bar)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 5
#
#[[3]]
#<simpleError in foo(x): no 6 for you>
#  
#[[4]]
#[1] 10

baz <- function(x) tryCatch({
  if (x == 6) stop("no 6 for you")
  x
}, error = function(e) e)
lapply(l, baz)
#also works
Run Code Online (Sandbox Code Playgroud)