Convert “Jan.2008” to date variable

一曲冷凌霜 提交于 2021-02-16 04:04:46

问题


How would I convert the following character variables to dates?

strDates <- c("Jan.2008", "Feb.2008")
str(strDates)
chr [1:2] "Jan.2008" "Feb.2008"

dates <- as.Date(strDates, "%b %Y")
str(dates)
Date[1:2], format: NA NA

Any assistance would be greatly appreciated


回答1:


A Date requires a day element as well, so you can add that to the input string with paste:

full.dates <- paste("01", strDates, sep = ".")

Specify the template correctly, including separator tokens:

as.Date(full.dates, "%d.%b.%Y")
[1] "2008-01-01" "2008-02-01"



回答2:


To form a valid 'date', you also need a day which your data was lacking. So we add one, and we simply use an arbitrary day (here: first of the month):

R> strDates <- c("Jan.2008", "Feb.2008")
R> strptime(paste("01", strDates), "%d %b.%Y")
[1] "2008-01-01" "2008-02-01"
R> 


来源:https://stackoverflow.com/questions/9322923/convert-jan-2008-to-date-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!