如何从2010-01-01到2015-12-31提取每个月的第一个星期一?
我们可以使用lubridate
,wday
测试这是否是星期一,并day
测试这是否是该月的第一周:
library(lubridate) x <- seq(ymd("2010-01-01"),ymd("2015-12-31"),by="1 day") x[wday(x,label = TRUE) == "Mon" & day(x) <= 7]
或者在base-r(@ DavidArenburg的评论)
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]
输出(五个第一结果)
[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"
另一个apprach:使用Boost Date_Time库:
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"...