I have a source column in a dataframe, where dates may be either in "dd.mm.yyyy" format or in Excel format of 5-digit number. Hence, I would like to check with ifelse
, how the element looks like with str_detect
and then use appropriate conversion for each.
df$date <- ifelse(str_detect(df$date, "[0-9]{2}.[0-9]{2}.[0-9]{4}") == TRUE,
as.Date(df$date, format = "%d.%m.%Y"),
as.Date(as.numeric(df$date), origin = "1899-12-30"))
While both conversion functions work as intended on their own, when I put them into ifelse
statement, I got weird results - basically 1st Jan 2019 becomes "17897". Can somebody explain why is that happening and how I can make it work? Thanks
Edit: code snippet
df <- c("01.01.2019", "43867")
df <- ifelse(str_detect(df, "[0-9]{2}.[0-9]{2}.[0-9]{4}") == TRUE,
as.Date(df, format = "%d.%m.%Y"),
as.Date(as.numeric(df), origin = "1899-12-30"))
Desired output: "2019-01-01" "2020-02-06"
Resulted output 17897 18298
Where if I apply first (yes) function without ifelse
, I will get "2019-01-01" NA
, and no function results in NA "2020-02-06"