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

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

    One could try to keep it simple rather than to make it complicated:

    • Use the vectorised date parsing
    R> as.Date( c("2010-04-06", "foo", "2010-04-08") )
    [1] "2010-04-06" NA           "2010-04-08"
    

    You can trivially wrap na.omit() or whatever around it. Or find the index of NAs and extract accordingly from the initial vector, or use the complement of the NAs to find the parsed dates, or, or, or. It is all here already.

    • You can make your testFunction() do something. Use the test there -- if the returned (parsed) date is NA, do something.

    • Add a tryCatch() block or a try() to your date parsing.

    The whole things is a little odd as you go from a one-type data structure (vector of chars) to something else, but you can't easily mix types unless you keep them in a list type. So maybe you need to rethink this.

提交回复
热议问题