Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Present Dates in Different Formats in R

You’ve probably noticed in R that as.Date() is fairly prescriptive in its defaults: It expects the date to be formatted in the order of year, month, and day. Fortunately, R allows you flexibility in specifying the date format.

By using the format argument of as.Date(), you can convert any date format into a Date object. For example, to convert “27 July 2012” into a date, use the following:

> as.Date("27 July 2012", format="%d %B %Y")
[1] "2012-07-27"

This rather cryptic line of code indicates that the date format consists of the day (%d), full month name (%B), and the year with century (%Y), with spaces between each element.

Here are some of the many date formatting elements that you can use to specify dates. You can access the full list by typing ?strptime in your R console.

Format Description
%Y Year with century.
%y Year without century (00–99). Values 00 to 68 are prefixed by 20, and values 69 to 99 are prefixed by 19.
%m Month as decimal number (01–12).
%B Full month name in the current locale. (Also matches abbreviated name on input.)
%b Abbreviated month name in the current locale. (Also matches full name on input.)
%d Day of the month as a decimal number (01–31). You don’t need to add the leading zero when converting text to Date, but when you format a Date as text, R adds the leading zero.
%A Full weekday name in the current locale. (Also matches abbreviated name on input.)
%a Abbreviated weekday name in the current locale. (Also matches full name on input.)
%w Weekday as decimal number (0–6, with Sunday being 0).

Try the formatting codes with another common date format, “27/7/2012” (that is, day, month, and year separated by a slash):

> as.Date("27/7/12", format="%d/%m/%y")
[1] "2012-07-27"
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!