Working with Dates Using lubridate
This week is all about special data types in R. Similar to the tools you learned last week for working with factors, this week you are going to learn about tools for working with dates. By the end of this week you should be able to:
- recognize structure of how dates were stored (e.g., day-month-year, month-day-year, month-day-year-hours-minutes)
- specify time zones for data variables
- extract elements of a date variable
- create intervals of time using the %–% operator
- check if a date is within an interval using the %within% operator
📽 Watch Videos: 20 minutes
📖 Readings: 60-75 minutes
✅ Preview Activities: 1
1 Working with Dates
In order to fill in an important part of our toolbox, we need to learn how to work with date variables. These variables feel like they should be simple and intuitive given we all work with schedules and calendars everyday. However, there are little nuances that we will learn to make working with dates and times easier.
📖 Required Reading: R4DS – Dates and Times
A more in-depth discussion of the POSIXlt and POSIXct data classes.
A tutorial on lubridate - scroll down for details on intervals if you have trouble with
%within%
and%--%
✅ Check-in 5.2: Functions from lubridate
The lubridate cheatsheet is in Week 5 of your coursepack! If you do not have a coursepack I would strongly recommending printing the lubridate cheatsheet.
Q1: Which of the following is true about the year()
function?
year()
creates a duration object to be added to a datetimeyear()
extracts the year of a datetime object
Q2: What tz
would you use for San Luis Obispo? Use the exact input you would use in R!
Q3: Which of the following is true about the %within%
operator?
- it checks if a date is included in an interval
- it returns a logical value
- it creates an interval with a start and end time
Q4: Which of the following is true about the %--%
operator?
- it creates an interval with a start and end time
- it returns a logical value
- it checks if a date is included in an interval
Q5: What day does the make_date()
function use as default if no day
argument is provided?