You can use the following methods to get the first or last day of the month for some date in R using functions from the lubridate package:
Method 1: Get First Day of Month
library(lubridate) df$first_day month')
Method 2: Get Last Day of Month
library(lubridate) df$last_day month') - days(1)
The following examples show how to use each method in practice with the following data frame:
#create data frame df frame(date=c('2022-01-05', '2022-02-18', '2022-03-21', '2022-09-15', '2022-10-30', '2022-12-25'), sales=c(14, 29, 25, 23, 39, 46)) #view data frame df date sales 1 2022-01-05 14 2 2022-02-18 29 3 2022-03-21 25 4 2022-09-15 23 5 2022-10-30 39 6 2022-12-25 46
Example 1: Get First Day of Month Using lubridate
The following code shows how to use the floor_date() function from the lubridate package to get the first day of the month for each value in the date column:
#add new column that contains first day of month
df$first_day month')
#view updated data frame
df
date sales first_day
1 2022-01-05 14 2022-01-01
2 2022-02-18 29 2022-02-01
3 2022-03-21 25 2022-03-01
4 2022-09-15 23 2022-09-01
5 2022-10-30 39 2022-10-01
6 2022-12-25 46 2022-12-01
Notice that the values in the new first_day column contain the first day of the month for each value in the date column.
Note: We used the ymd() function to first convert the strings in the date column to a recognizable date format.
Example 2: Get Last Day of Month Using lubridate
The following code shows how to use the ceiling_date() function from the lubridate package to get the last day of the month for each value in the date column:
#add new column that contains last day of month
df$last_day month') - days(1)
#view updated data frame
df
date sales last_day
1 2022-01-05 14 2022-01-31
2 2022-02-18 29 2022-02-28
3 2022-03-21 25 2022-03-31
4 2022-09-15 23 2022-09-30
5 2022-10-30 39 2022-10-31
6 2022-12-25 46 2022-12-3122-12-01
Notice that the values in the new last_day column contain the last day of the month for each value in the date column.
Refer to the lubridate documentation page for more date formatting options.
Additional Resources
The following tutorials explain how to perform other common tasks in R:
How to Convert Date to Numeric in R
How to Extract Month from Date in R
How to Add and Subtract Months from a Date in R