0

I wanna extract the date from a string. When I run it step by step, it works great as below

as.Date(strptime(substr("44132219721105202X",7,14),format="%Y%m%d"))
[1] "1972-11-05"

But I wanna use it in ifelse function, because I have a column strings to do that. But it doesn't work.

ifelse(nchar("44132219721105202X", type = "bytes", allowNA = FALSE, keepNA = NA)==18,as.Date(strptime(substr("44132219721105202X",7,14),format="%Y%m%d")),"44132219721105202X")
  • 2
    You are seeing one of the classic *problems* with `ifelse`: it drops class. (You are also using it incorrectly: both the 'yes' and 'no' results should be the same class, whereas here you have `Date` and `character`.) If you're using `dplyr`, consider using `dplyr::if_else`. If you're using `data.table`, consider using `data.table::fifelse`. Both of those are more reliable than base R's `ifelse`. – r2evans Mar 11 '20 at 15:21
  • 1
    As an example of how `ifelse` fails, try `ifelse(T, Sys.time(), Sys.time())`. It should *"obviously"* return `POSIXt` yet it returns `numeric`. – r2evans Mar 11 '20 at 15:21
  • Ultimately, while this is very frustrating, it is also a FAQ and a duplicate ... https://stackoverflow.com/q/6668963, https://stackoverflow.com/q/24983470, and https://stackoverflow.com/q/27856735. – r2evans Mar 11 '20 at 15:23
  • @ r2evans Thanks a lot. I solved as ```dplyr::if_else(nchar("44132219721105202X", type = "bytes", allowNA = FALSE, keepNA = NA)==18, as.Date(strptime(substr("44132219721105202X",7,14),format="%Y%m%d")),as.Date(NA))``` . Unfortunately, we compensate a little bit, since sometimes we still needs two classes in the process. – user11320718 Mar 12 '20 at 09:40
  • *"we still needs two classes"*: that sounds like inconsistent data, which can be a hard thing in data-science-y things to troubleshoot. Robust code/functions will "always" give you a single class for a variable, mixing classes is rarely justified and often the cause of angst and/or inconsistent/irreproducible results. – r2evans Mar 12 '20 at 14:44
  • @r2evans I mean it's a medium process. Definitely, the class should be concordant. – user11320718 Mar 12 '20 at 18:02

0 Answers0