as.Date with dates in format m/d/y in R

2019-01-20 13:37发布

A client sent me an Excel file with dates formatted as e.g 3/15/2012 for March 15. I saved this as a .csv file and then used

camm$Date <- as.Date(camm$Date, "%m/%d/%y")

but this gave me values starting in the year 2020!

I tried to reformat the dates in the original csv file so that they were e.g. 03/14/2013 but was unable to do so.

Any help appreciated

标签: r date r-faq
3条回答
老娘就宠你
2楼-- · 2019-01-20 14:26

To complete the picture, you might also try the recently introduced (2016-09) package anytime which takes advantage of the Boost C++ libraries:

anytime::anytime("3/15/2012")
#[1] "2012-03-15 CET"
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-20 14:27

Use capital Y in as.Date call instead. This should do the trick:

> as.Date("3/15/2012", "%m/%d/%Y")
[1] "2012-03-15"

From the help file's examples you can realize when year is full specified you should use %Y otherwise %y for example:

> dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
> as.Date(dates, "%m/%d/%y")
[1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28" "1992-02-01"

You can see that in your example the Year format is 2012 then you should use %Y, and in the other example (taken from the as.Date help file) Year format is 92 then using %y is the correct way to go. See as.Date for further details.

查看更多
劫难
4楼-- · 2019-01-20 14:27

You might also give a try to the lubridate package if you do not want to deal with the hieroglyphics :)

> library(lubridate)
> parse_date_time('3/15/2012', 'mdy')
 1 parsed with %m/%d/%Y
[1] "2012-03-15 UTC"

PS.: of course I do not encourage anyone to use any extra dependencies, this answer was just posted here as an alternative (and quick to remeber) solution

查看更多
登录 后发表回答