Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change multiple Date formats in same column?

Tags:

What I've got so far is a dataframe column with dates in different character formats. A few appear in the %d.%m.%Y pattern, some in %m/%d/%Y :

data$initialDiagnose = as.character(data$initialDiagnose) data$initialDiagnose[1:10]  [1] "14.01.2009" "9/22/2005"  "4/21/2010" "28.01.2010" "09.01.2009" "3/28/2005" "04.01.2005" "04.01.2005" "9/17/2010" "03.01.2010" 

I want them as Date() in one format, but R refuses of course.
So I tried at first to change them by the separator:

data$initialDiagnose[grep('/', data$initialDiagnose)] = as.character.Date(data$initialDiagnose[grep('/', data$initialDiagnose)], format = '%m/%d/%Y') 

Analog to the '.' dates. But it didn't work.

How can I change them all to one format, that I can work with them?

like image 707
Rob Avatar asked Dec 07 '12 13:12

Rob


People also ask

How do I change the format of multiple dates in the same column in Excel?

Select the cells you want to format. Press CTRL+1. In the Format Cells box, click the Number tab. In the Category list, click Date, and then choose a date format you want in Type.


1 Answers

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 
like image 108
MattBagg Avatar answered Oct 10 '22 18:10

MattBagg