Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract first Monday of every month

Tags:

date

r

How can I extract the first Monday of every month from 2010-01-01 to 2015-12-31?

like image 792
user5740635 Avatar asked Nov 28 '22 23:11

user5740635


2 Answers

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"
like image 162
scoa Avatar answered Dec 05 '22 13:12

scoa


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"...
like image 23
lukeA Avatar answered Dec 05 '22 12:12

lukeA