user4180911
user4180911

Reputation:

R TryCatch not working with lapply

I am trying to apply a function to a list of files using lapply (I make a few operations on a data frame and then write plots). The problem is that it seems that if the function raises an error for a file

(a calculation on the data frame cannot be made)

, the iteration stops.

I used tryCatch both within the function

ee = function(i){return(tryCatch(..., error=function(e) NULL))}

and in lapply

lapply(list.files(path), tryCatch(ee, error=function(e) NULL)))

but in either case, I continue to get the error detected and the iteration stopped. Any idea? Thanks.

Upvotes: 4

Views: 1845

Answers (2)

RmK
RmK

Reputation: 137

define ee like that

ee <- function (i) {
  return(tryCatch(....., error=function(e) NULL))
}

and then call lapply that way

lapply(list.files(path), ee)

Upvotes: 0

Roland
Roland

Reputation: 132854

I believe your first example should work in principle, but don't understand what you are doing with the ellipses there.

Here is a simple minimal example:

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

Upvotes: 5

Related Questions