Reputation: 314
the goal is quite straightforward, I want a vector made of all the dates in this month.
Why?
Because I'll later be able to transform this vector and get the first day of the month, or alternatively, a vector with just the 1st and 16th of the month, or even a vector with all the Mondays of the month... list goes on, but POSIXlt should serve us better since it also stores the weekday.
require("lubridate")
v.d.CheckDates <- as.POSIXlt(seq(as.POSIXlt(Sys.Date() - days(31)), length.out=62, by="day"))
v.d.CheckDates[v.d.CheckDates$mon == as.numeric(format(Sys.Date() , format = "%m")) - 1]
it's basically creating a 62 day vector centered on today (first line) and then trimming the other months (second line)
So, does anyone have a more cleaver and more efficient (preferably also one liner) way of doing it?
Upvotes: 1
Views: 652
Reputation: 1037
Package timeperiodsR has a handy function for that :
timeperiodsR::this_month(part = "sequence")
Upvotes: 2
Reputation: 388982
You can use floor_date
to get 1st date of current month, ceiling_date
to get 1st date of next month subtract - 1
to get last day of current month and create sequence.
library(lubridate)
todays_date <- Sys.Date()
seq(floor_date(todays_date, 'month'),
ceiling_date(todays_date, 'month') - 1, by = 1)
Also other similar variations,
floor_date(todays_date, 'month') + 1:days_in_month(todays_date) - 1
seq(floor_date(todays_date, 'month'),
length.out = days_in_month(todays_date), by = 1)
This returns object of class 'Date'
, there are function in base R as well as lubridate
to get whichever part of Date you want.
Upvotes: 2