2016-01-26 40 views
0

有幾個類似的問題我已經看到,試圖回答這個問題,但沒有一個對我的問題是完全正確的。如何將字符日期轉換爲R格式

Converting dates from excel to R

How do I convert dates in this format to a date class in R?

我有日期:

dates <- c("16 Jan 63", "16 Jan 73", "17 Jul 62", "25 Aug 60") 

所有年開始的 「19-」

我認爲使用明顯的解決方案是as.Date,或strptime功能:

dates <- as.Date(dates, "%d %b %y") 
dates 
[1] "2063-01-16" "2073-01-16" "2062-07-17" "2060-08-25" 

正如您所看到的,問題出在今年,沒有一個正確轉換。

我的下一個解決方案是使用strsplit

dates <- c("16 Jan 63", "16 Jan 73", "17 Jul 62", "25 Aug 60") 
new.dates <- strsplit(dates, " ") 
new.dates 
[[1]] 
[1] "16" "Jan" "63" 

[[2]] 
[1] "16" "Jan" "73" 
# etc 

然而,當我嘗試粘貼「19」在今年的前,然後塌陷它們放回相同的字符的問題開始。

new.dates[?] <- paste0("19", new.dates[?]) 
new.dates[?] <- paste(new.dates[?], collapse = " ") 

我不知道什麼尺寸應該是粘貼。最後,我想用格式化日期:

new.dates <- strptime(new.dates, "%d %b %Y") 
new.dates <- as.Date(new.dates) 

如果任何人有如何做到這一點的任何建議,或已回答的問題的鏈接,這將是大加讚賞。

+1

你可以做'as.Date(日期, 「%d%B%Y」)+ lubridate ::年(1900年)' –

回答

0

我們可以嘗試

as.Date(format(as.Date(dates,"%d %B %y"), "19%y-%m-%d")) 
相關問題