How to tell lapply to ignore an error and process the next thing in the list?

后端 未结 4 1487
失恋的感觉
失恋的感觉 2020-11-27 13:41

I have an example function below that reads in a date as a string and returns it as a date object. If it reads a string that it cannot convert to a date, it returns an erro

4条回答
  •  不知归路
    2020-11-27 14:28

    Assuming the testFunction() is not trivial and/or that one cannot alter it, it can be wrapped in a function of your own, with a tryCatch() block. For example:

    > FaultTolerantTestFunction <- function(date_in) {
    +    tryCatch({ret <- testFunction(date_in);}, error = function(e) {ret <<- NA});
    +    ret
    + }
    > FaultTolerantTestFunction('bozo')
    [1] NA
    > FaultTolerantTestFunction('2010-03-21')
    [1] "2010-03-21"
    

提交回复
热议问题