Creating and examining date objects

The base R package provides date functionality. This grab-bag recipe shows you several date-related operations in R. R internally represents dates as the number of days from 1 January, 1970.

Getting ready

In this recipe, we will only be using features from the base package and not from any external data. Therefore, you do not need to perform any preparatory steps.

How to do it...

Internally, R represents dates as the number of days from 1 January, 1970:

  1. Get today's date:
    > Sys.Date()
  2. Create a date object from a string:
    > # Supply year as two digits > # Note correspondence between separators in the date string and the format string > as.Date("1/1/80", format = "%m/%d/%y") [1] "1980-01-01" > # Supply year as 4 digits ...

Get R: Recipes for Analysis, Visualization and Machine Learning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.