2

I have extracted data to a data frame with mixed format dates that need consolidated. The structure of the data frame is as follows:

dateDF <- structure(list(id = 1:7, value = c(5813L, 8706L, 4049L, 5877L, 
1375L, 2223L, 3423L), date = structure(c(4L, 3L, 2L, 1L, 7L, 
6L, 5L), .Label = c("??:?? 05-Dec-11", "??:?? 06-Dec-11", "??:?? 07-Dec-11", 
"??:?? 19-Dec-11", "30/12/2011 16:00", "30/12/2011 16:45", "31/12/2011 19:10"
), class = "factor")), .Names = c("id", "value", "date"), row.names = c(NA, 
-7L), class = "data.frame")

I have used dateDF$date <- str_replace(string=dateDF$date, pattern='\\?\\?\\:\\?\\? ', '12:00 ') to produce:

id  value   date
1   5813    12:00 19-Dec-11
2   8706    12:00 07-Dec-11
3   4049    12:00 06-Dec-11
4   5877    12:00 05-Dec-11
5   1375    31/12/2011 19:10
6   2223    30/12/2011 16:45
7   3423    30/12/2011 16:00

I now need to convert the top 4 style dates with format hh:mm dd-mmm-yy to a format consistent with the bottom three date formats dd/mm/yyyy hh:mm for each case where the first format exists in the column.

Any help is appreciated.

J.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
John
  • 41,131
  • 31
  • 82
  • 106

1 Answers1

5

If you know that you only have those two formats, you can first identify them (the first one has alphabetic characters in it, the other does not) and convert accordingly.

dateDF$date <- as.POSIXlt( 
  dateDF$date, 
  format = ifelse( 
    grepl("[a-z]", d$date), 
    "%H:%M %d-%b-%y", 
    "%d/%m/%Y %H:%M" 
  ) 
)
Vincent Zoonekynd
  • 31,893
  • 5
  • 69
  • 78