Dates

Ranae Dietzel & Andee Kaplan

Dates in the Tidyverse

lubridate

Life before lubridate was so hard.

We will not even venture down this road.

When you encounter non-lubridate date code, be strong.

Write dates as YYYY-MM-DD

xckd.com

When is the last time you recieved a date in the right format?

Getting R to recognize a date is usually the first step

dates<-c("10/20/2016", "10/21/2016", "10/22/2016")
mdy(dates)
## [1] "2016-10-20" "2016-10-21" "2016-10-22"

Now we are good.

parse_date_time

parse_date_time("2014-09-24 15:23:10", orders="ymd hms")  
## [1] "2014-09-24 15:23:10 UTC"
parse_date_time("09/24/2014 15-23-10", orders="mdy hms")
## [1] "2014-09-24 15:23:10 UTC"
parse_date_time("24 09 2014 15 23 10", orders="dmy hms")
## [1] "2014-09-24 15:23:10 UTC"
parse_date_time("24-09-14 15-23-10", orders="dmy hms")
## [1] "2014-09-24 15:23:10 UTC"
parse_date_time("Sep 24, 2014 15:23:10", orders="mdy hms")
## [1] "2014-09-24 15:23:10 UTC"

Now we can isolate components of our dates

month("2016-10-21")
## [1] 10
day("2016-10-21")
## [1] 21
year("2016-10-21")
## [1] 2016

Day of year!

yday("2016-10-21")
## [1] 295
yday(mdy(dates))
## [1] 294 295 296

Also handles intervals

For example, when can Andee prepare for her prelim?

now<-Sys.time()
prelim<-"2016-10-25 09:00:00 CDT"
prep<-now %--% prelim 
prep
## [1] 2016-10-21 14:58:35 UTC--2016-10-25 09:00:00 UTC

When will Ranae be at a Software Carpentry Instructor workshop?

depart<-"2016-10-23 12:00:00 CDT"
return<-"2016-10-25 20:00:00 CDT"
workshop<- depart %--% return
workshop
## [1] 2016-10-23 12:00:00 UTC--2016-10-25 20:00:00 UTC

Will Andee and Ranae be occupied at the same time?

int_overlaps(prep, workshop)
## [1] TRUE

When will Andee and Ranae both be unavailable?

setdiff(prep, workshop)
## [1] 2016-10-21 14:58:35 UTC--2016-10-23 12:00:00 UTC

Eric Hare will teach class at 2016-10-24 10:00:00.

If anyone drove a time machine, they would crash -Grolemund

The length of months and years change so often that doing arithmetic with them can be unintuitive. Consider a simple operation, January 31st + one month. Should the answer be

  1. February 31st (which doesn’t exist)
  2. March 4th (31 days after January 31), or
  3. February 28th (assuming its not a leap year)

Lubridate does arithmetic with dates, but you still have to think about it and make decisions about what you really mean and want.

However, there are helpful functions such as:

How long does Andee have to prepare for her prelim?

as.period(prep %% months(1))
## [1] "3d 18H 1M 24.9760739803314S"

More practice

Pull in lab materials for practice with lubridate and dplyr.