dudemonkey dudemonkey - 1 year ago 162
R Question

Formatting M/D/YY dates in R

I have a column in R that was exported from Excel and it's a datetime of the format "4/3/16" (ie, M/D/YY). There are no leading zeros in the day or month fields and I'm not sure how to convert this type of value to a date field in R.

I'm new to R so this might be a something obvious that I don't know. Is R the wrong tool to use for data analysis involving dates?

Answer Source

Format strings cope fine with that, and base R is all you need:

R> d <- as.Date("4/3/16", "%m/%d/%y")
R> d
[1] "2016-04-03"

The only thing to remember, really, is that %y is for two-digit years whereas %Y is for four-digit years. All the gory details are in the corresponding help pages for as.Date(), strptime() and friends.

And repeat after me: Friends never let friends parse dates with string functions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download