Search code examples
rdatedatetime

How to convert character to date with two different types of date formats in R?


I have a huge dataset with over 2 million obs and all column's classes are character type. I need to convert one of them to date format dd/mm/yyyy, but the dates are written like this:

dates <- c("2022-04-08", "26/01/2021", "14/07/2021", "2021-12-27")

I've already tried some explanations I found in other posts but none of them seemed to work for me. One groupe of dates always turns into NA.


Solution

  • You can do something like:

    format_ymd  <- as.Date(dates, format = "%Y-%m-%d")
    format_dmy  <- as.Date(dates, format = "%d/%m/%Y")
    as.Date(ifelse(is.na(format_ymd), format_dmy, format_ymd), origin = "1970-01-01")
    # [1] "2022-04-08" "2021-01-26" "2021-07-14" "2021-12-27"