How to Get First or Last Day of Month in R with lubridate and base R
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Introduction
When working with dates in R, you’ll often need to find the first or last day of the current month or any given month. There are a couple easy ways to do this using the lubridate package and base R functions. In this post, I’ll show you how.
Examples
Using lubridate
The lubridate package makes working with dates in R much easier. It has a number of helper functions for manipulating and extracting info from Date and POSIXct objects.
To get the first day of the current month, you can use floor_date()
and pass it the current date:
library(lubridate) today <- Sys.Date() # or Sys.time() for POSIXct first_day <- floor_date(today, unit = "month") first_day
[1] "2024-02-01"
This will return a Date object with the first day of the month.
To get the last day, use ceiling_date()
instead:
last_day <- ceiling_date(today, unit = "month") - days(1) last_day
[1] "2024-02-29"
You can also pass any Date object to these functions to get the first or last day of that month:
date <- ymd("2023-06-15") floor_date(date, "month") # 2023-06-01
[1] "2023-06-01"
ceiling_date(date, "month") - days(1) # 2023-06-30
[1] "2023-06-30"
The lubridate functions make this really easy!
Base R Methods
You can also get the first and last day of month using just base R functions.
For the first day, use as.Date()
with format()
and pass it the year, month, and day 1:
first_day <- as.Date(format(today, "%Y-%m-01")) first_day
[1] "2024-02-01"
For the last day, we can use 0
as the day which will give the last day of the month:
last_day <- as.Date((format(today + months(1), "%Y-%m-01")))-1 last_day
[1] "2024-02-29"
A bit more work than lubridate, but good to know you can do this with just base R.
I hope this helps you easily get the first and last day of the month in your own date analyses in R! Let me know if you have any other questions.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.