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.
Cet exercice fait partie du cours
Working with Dates and Times in R
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_seqtojan_31. Notice what happens to any month where the 31st doesn't exist - Now add
month_seqtojan_31using the%m+%operator. - Try subtracting
month_seqfromjan_31using the%m-%operator.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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-%
___ ___ ___