The tricky thing about months
What should ymd("2018-01-31") + months(1)
return? Should it be 30, 31 or 28 days in the future? Try it. In general lubridate
returns the same day of the month in the next month, but since the 31st of February doesn't exist lubridate
returns a missing value, NA
.
There are alternative addition and subtraction operators: %m+%
and %m-%
that have different behavior. Rather than returning an NA
for a non-existent date, they roll back to the last existing date.
You'll explore their behavior by trying to generate a sequence for the last day in every month this year.
This exercise is part of the course
Working with Dates and Times in R
Exercise instructions
We've put jan_31
, the date for January 31st this year in your workspace.
- Start by creating a sequence of 1 to 12 periods of 1 month.
- Add
month_seq
tojan_31
. Notice what happens to any month where the 31st doesn't exist - Now add
month_seq
tojan_31
using the%m+%
operator. - Try subtracting
month_seq
fromjan_31
using the%m-%
operator.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# A sequence of 1 to 12 periods of 1 month
month_seq <- ___
# Add 1 to 12 months to jan_31
___ + ___
# Replace + with %m+%
___ ___ ___
# Replace + with %m-%
___ ___ ___