MCS
MCS

Reputation: 1101

Inconsistent dates formatting (lubridate fail)

I have a vector of inconsistent dates, including (mainly) these three formats: "%d/%m/%y", "%m/%d/%y" and "%d/%m/%Y"

I tried to implement this:

df <- as.data.frame(c("30/12/00","7/31/09","17/09/2008"),col.names = "original_date")

guess_date <- function(x){
  require(lubridate)
  guess <- guess_formats(x, c("mdy","dmy"))
  date <- as.Date(x, guess)[1]
  return(date)
}

df$date <- lapply(df$original_date, guess_date)

Upvotes: 1

Views: 191

Answers (1)

akrun
akrun

Reputation: 887911

We can pass it with parse_date_time

library(lubridate)
parse_date_time(df$original_date, 
    guess_formats(as.character(df$original_date), c("mdy", "dmy", "dmY")))
#[1] "2000-12-30 UTC" "2009-07-31 UTC" "2008-09-17 UTC"

Upvotes: 2

Related Questions