Search code examples
rlubridate

Converting Dates in R in both Directions


I am trying to convert date objects into a date class using lubridate. These are the following dates in the "wrong" format"

wrong_format_date1 <- "01-25-1999"
wrong_format_date2 <- 25012005
wrong_format_date3 <- "2005-05-31"

But I would like them in this format:

"1999-01-25"
"2005-01-25"
"2005-05-31"

Can someone please assist me with this?


Solution

  • Try this. Use parse_date_time() from lubridate where you can define a vector with possible formats so that you get your strings parsed as dates. Here the code:

    library(lubridate)
    #Data
    wrong_format_date1 <- "01-25-1999"
    wrong_format_date2 <- 25012005
    wrong_format_date3 <- "2005-05-31"
    #Dataframe
    df <- data.frame(v1=c(wrong_format_date1,wrong_format_date2,wrong_format_date3),stringsAsFactors = F)
    #Code
    df$Date <- as.Date(parse_date_time(df$v1, c("mdY", "dmY","Ymd")))
    

    Output:

              v1       Date
    1 01-25-1999 1999-01-25
    2   25012005 2005-01-25
    3 2005-05-31 2005-05-31