2

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?

Community
  • 1
  • 1
DJJ
  • 2,481
  • 2
  • 28
  • 53

1 Answers1

6

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))
}
Roland
  • 127,288
  • 10
  • 191
  • 288
  • Nice catch! Many thanks. I wonder how it works though? The function is called but the error is not catched. – DJJ Oct 17 '16 at 15:30
  • Check the output of `tryCatch({tmpfun},error=function(e) NULL)`. The expression you pass to `tryCatch` doesn't cause an error and is thus returned unchanged. – Roland Oct 17 '16 at 15:39