Dates are generally part of database that one works on. Till now everyone knows how to get year, month, day, week from given date. But most of the time working on actual projects need automation of codes and one might need first or last date of a month to be automatically taken from given dates.
Lubridate package has functions like floor_date() and ceiling_date() which gives exactly what we want.
floor_date takes a date-time object and rounds it down to the nearest integer value of the specified time unit. Users can specify whether to round down to the nearest second, minute, hour, day, week, month, or year.
ceiling_date takes a date-time object and rounds it up to the nearest integer value of the specified time unit. Users can specify whether to round up to the nearest second, minute, hour, day, week, month, or year.
floor_date(x, unit = c(“second”, “minute”, “hour”, “day”, “week”, “month”, “year”))
ceiling_date(x, unit = c(“second”, “minute”, “hour”, “day”, “week”, “month”, “year”))
Arguments :
x a vector of date-time objects
unit a character string specifying the time unit to be rounded to. Should be one of “second”, “minute”, “hour”, “day”, “week”, “month”, or “year.”
#Install and load package lubridate
install.packages("lubridate")
library(lubridate)
x <- as.Date("2021-02-05")
#Get the start date of the month
floor_date(x,"month")
## [1] "2021-02-01"
#Get the end date of the month
#subtract with 1, as ceiling_date() returns start date of next month
ceiling_date(x,"month")-1
## [1] "2021-02-28"
#start of that week
floor_date(x, "week")
## [1] "2021-01-31"
#start of next week
ceiling_date(x, "week")
## [1] "2021-02-07"
date.end.month <- seq(as.Date("2021-02-01"),length=4,by="months")- 1
date.end.month
## [1] "2021-01-31" "2021-02-28" "2021-03-31" "2021-04-30"
The by= argument to the seq function can be specified either as a difftime value, or in any units of time that the difftime function accepts, making it very easy to generate sequences of dates.
All the date classes except for chron will accept an integer before the interval provided as a by= argument. We could create a sequence of dates separated by two weeks from June 1, 2000 to August 1, 2000 as follows:
seq(as.Date('2020-6-1'),to=as.Date('2020-8-1'),by='2 weeks')
## [1] "2020-06-01" "2020-06-15" "2020-06-29" "2020-07-13" "2020-07-27"