How to change multiple Date formats in same column?

I like lubridate for its ease of use:

library(lubridate) 

# note added ugly formats below
data <- data.frame(initialDiagnose = c("14.01.2009", "9/22/2005", 
        "4/21/2010", "28.01.2010", "09.01.2009", "3/28/2005", 
        "04.01.2005", "04.01.2005", "Created on 9/17/2010", "03 01 2010"))

mdy <- mdy(data$initialDiagnose) 
dmy <- dmy(data$initialDiagnose) 
mdy[is.na(mdy)] <- dmy[is.na(mdy)] # some dates are ambiguous, here we give 
data$initialDiagnose <- mdy        # mdy precedence over dmy
data
#   initialDiagnose
#       2009-01-14
#       2005-09-22
#       2010-04-21
#       2010-01-28
#       2009-09-01
#       2005-03-28
#       2005-04-01
#       2005-04-01
#       2010-09-17
#       2010-03-01

Leave a Comment