26 Dates in R

26.1 Introduction

Working with dates and time can be very frustrating. In general, work with the least cumbersome class. That means if your variable is years, store it as an integer; there’s no reason to use a date or date-time class. If your variable does not involve time, use the Date class in R.

26.2 Converting to Date class

You can convert character data to Date class with as.Date():

Note that the two appear the same, although the class is different:

## [1] "2018-10-12"
## [1] "2018-10-12"
## [1] "character"
## [1] "Date"

If the date is not in YYYY-MM-DD or YYYY/MM/DD form, you will need to specify the format to convert to Date class, using conversion specifications that begin with %, such as:

## [1] "2005-01-06"

For a list of the conversion specifications available in R, see ?strptime.

The tidyverse lubridate makes it easy to convert dates that are not in standard format with ymd(), ydm(), mdy(), myd(), dmy(), and dym() (among many other useful date-time functions):

## [1] "1907-04-13"

Try as.Date("April 13, 1907") and you will see the benefit of using a lubridate function.

26.3 Working with Date Class

It is well worth the effort to convert to Date class, because there’s a lot you can do with dates in a Date class that you can’t do if you store the dates as character data.

Number of days between dates:

## Time difference of 305 days

Compare dates:

## [1] TRUE

Note that Sys.Date() returns today’s date as a Date class:

## [1] "2019-11-13"
## [1] "Date"

R has functions to pull particular pieces of information from a date:

## [1] "Wednesday"
## [1] "Wed"
## [1] "November"
## [1] "Nov"
## [1] "Q4"

The lubridate package provides additional functions to extract information from a date:

## [1] 2019
## [1] 317
## [1] 11
## [1] Nov
## 12 Levels: Jan < Feb < Mar < Apr < May < Jun < Jul < Aug < Sep < ... < Dec
## [1] 13
## [1] 46
## [1] 4

26.4 Plotting with a Date class variable

Both base R graphics and ggplot2 “know” how to work with a Date class variable, and label the axes properly:

26.4.2 ggplot2

Note that unlike base Rread.csv(), readr::read_csv() automatically reads DATE in as a Date class since it’s in YYYY-MM-DD format:

Again, when the data is filtered, the x-axis labels switch from years to months.

26.4.2.1 Breaks, limits, labels

We can control the x-axis breaks, limits, and labels with scale_x_date():

(Yes, even in the tidyverse we cannot completely escape the % conversion specification notation. Remember ?strptime for help.)

26.5 Date and time classes

## [1] "2019-11-13 16:40:45 UTC"

Considering submitting a pull request to expand this section.







with