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

后端 未结 4 1473
失恋的感觉
失恋的感觉 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:27

    Use a tryCatch expression around the function that can throw the error message:

    testFunction <- function (date_in) {
      return(tryCatch(as.Date(date_in), error=function(e) NULL))
    }
    

    The nice thing about the tryCatch function is that you can decide what to do in the case of an error (in this case, return NULL).

    > lapply(dates2, testFunction)
    [[1]]
    [1] "2010-04-06"
    
    [[2]]
    NULL
    
    [[3]]
    [1] "2010-04-08"
    

提交回复
热议问题