Sometimes I create reports or analyses that I would like to run on a monthly base. It saves some time if I can simply let the report run, without you having to edit any variables. Lubridate has two really cool functions to get the first day or the last day of a particular month.
These functions are floor_date() and ceiling_date(). When you give them a date, you can have these functions return the lowest or highest possible, month, week or day.
floor_date(ymd('2019-05-12'), 'month') # returns '2019-05-01'
To get the first day and the last day of the month that has passed, we can do the following. We subtract 1 month from the current date and use the functions I described earlier.
start_date <- floor_date(Sys.Date() %m-% months(1), 'month')
end_date <- ceiling_date(Sys.Date() %m-% months(1), 'month') %m-% days(1)
Now you can use start_date and end_date wherever you want.
By the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. Hope it helps!
Great success!
i get 2020-09-01 as ceiling_date(Sys.Date()%m-% months(1), ‘month’) for today Sept 4 subtracting 1 gives the last day of August. R4.0.0.
Hi Vincent, thanks for reaching out.
Indeed, there was a mistake in the blog post.
ceiling_date(Sys.Date() %m-% months(1), ‘month’) %m-% days(1) is the correct answer.
Best regards
Roel
This helped me today with acquiring the last day of the month and then the first day of the next month in the prior year. Thank you.
You’re welcome!
Isn’t
“`r
start_date <- floor_date(today(), 'month') – months(1)
end_date <- floor_date(today(), 'month') – days(1)
“`
shorter and always gives the same result?
Where can I find documentation about: %m-%
Thank you!
Thanks a lot this was super helpful today !