How can I extract the first Monday of every month from 2010-01-01 to 2015-12-31?
We can use lubridate
, wday
to test if this is a Monday, and day
to test if this is the first week of the month:
library(lubridate)
x <- seq(ymd("2010-01-01"),ymd("2015-12-31"),by="1 day")
x[wday(x,label = TRUE) == "Mon" & day(x) <= 7]
or in base-r (@DavidArenburg's comment)
x <- seq(as.Date("2010-01-01"), as.Date("2015-12-31"), by = "day")
# You need to adapt "Monday" to the equivalent in your locale
x[weekdays(x) == "Monday" & as.numeric(format(x, "%d")) <= 7]
output (five first results)
[1] "2010-01-04 UTC" "2010-02-01 UTC" "2010-03-01 UTC" "2010-04-05 UTC" "2010-05-03 UTC" "2010-06-07 UTC"
Another apprach: using the Boost Date_Time library:
library(RcppBDT)
dates <- seq(as.Date("2010-01-01"), as.Date("2015-12-31"), by="1 month")
do.call(c, lapply(dates-1, getFirstDayOfWeekAfter, dow=Mon))
# [1] "2010-01-04" "2010-02-01" "2010-03-01" "2010-04-05" "2010-05-03"...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With