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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With