Incorrect Conversion of Date as a Factor to a Date

冷暖自知 提交于 2019-11-30 23:23:18
DateClosed <- factor(c("7/30/2007","12/12/2007", "5/8/2009"))
as.Date(DateClosed, format="%m/%d/%Y")

Produces:

[1] "2007-07-30" "2007-12-12" "2009-05-08"

Notice the capital "Y" in the format param. The lower case "y" is for 2 digit years, so as.Date reads the first two digits of the year token ("20"), and then assumes that refers to just the last two digits of the year, and adds the current date's century (also "20"), so you end up with dates in 2020.

Manipulating dates becomes really easy using lubridate package.

mdy(factor(c("7/30/2007","12/12/2007", "5/8/2009")))

"2007-07-30 UTC" "2007-12-12 UTC" "2009-05-08 UTC"

Or using parse_date_time with the same package:

parse_date_time(factor(c("7/30/2007","12/12/2007", "5/8/2009")),c('mdY'))
[1] "2007-07-30 UTC" "2007-12-12 UTC" "2009-05-08 UTC"
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!