DJJ DJJ - 4 days ago 4x
R Question

R allow error in lapply

related to this question. I wanted to build a simple lapply function that will output NULL if an error occur.

my first thought was to do something like

lapply_with_error <- function(X,FUN,...){
lapply(X,tryCatch({FUN},error=function(e) NULL))

tmpfun <- function(x){
if (x==9){
stop("There is something strange in the neiborhood")
} else {
paste0("This is number", x)

tmp <- lapply_with_error(1:10,tmpfun )

But tryCatch does not capture the error it seems. Any ideas?


You need to provide lapply with a function:

lapply_with_error <- function(X,FUN,...){    
  lapply(X, function(x, ...) tryCatch(FUN(x, ...),
                                      error=function(e) NULL))