2012-01-17 69 views
2

我已經將數據提取到具有需要整合的混合格式日期的數據幀。數據幀的結構如下:轉換數據幀中的混合日期格式

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") 

我已經使用dateDF$date <- str_replace(string=dateDF$date, pattern='\\?\\?\\:\\?\\? ', '12:00 ')生產:

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 

我現在需要與格式hh:mm dd-mmm-yy前4風格的日期轉換爲與一致的格式底部三種日期格式dd/mm/yyyy hh:mm,其中第一種格式存在於列中。

任何幫助表示讚賞。

J.

回答

4

如果你知道你只有這兩種格式,您可以先找出它們(第一個中有字母,其他沒有),並相應轉換。

dateDF$date <- as.POSIXlt( 
    dateDF$date, 
    format = ifelse( 
    grepl("[a-z]", d$date), 
    "%H:%M %d-%b-%y", 
    "%d/%m/%Y %H:%M" 
) 
) 
+0

Thanks @VincentZoonekynd,這太棒了。 – John 2012-01-18 00:55:03