每个月提取第一个星期一

5
我应该如何从2010年1月1日到2015年12月31日期间提取每个月的第一个星期一?

同样相关:http://stackoverflow.com/questions/23354069/how-to-figure-third-friday-of-a-month-in-r/23357399 - thelatemail
3个回答

15

我们可以使用lubridatewday来测试这是否为周一,使用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]

或者在基数为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"

7
使用基础R语言,可以使用以下代码生成2010年1月1日至2015年12月31日期间的所有星期一,并且日期在每个月的前7天内:x <- seq(as.Date("2010-01-01"), as.Date("2015-12-31"), by = "day") ; x[weekdays(x) == "Monday" & as.numeric(format(x, "%d")) <= 7] - David Arenburg

5
另一种方法:使用 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"...

4
这里提供了一个基于R语言的解决方案。只需要三行代码即可实现。在zoo快速参考手册中,有一个名为nextfri的单行函数,可以获取给定日期后或当天的下一个星期五。如果我们将该函数体内的每个5(星期五)替换为1(星期一),则可以获取给定日期后或当天的下一个星期一。(该公式不包括origin参数,但是由于zoo允许省略该参数,因此在这里我们包含它以使其无需任何包即可运行。)
# given "Date" class vector x return same date if Mon or next Mon if not
nextmon <- function(x) 7 * ceiling(as.numeric(x-1+4)/7) + as.Date(1-4, origin="1970-01-01")

# all first of months between the indicated dates
firsts <- seq(as.Date("2010-01-01"), as.Date("2015-12-31"), "month")

# first Monday in each month
nextmon(firsts)

`给予:`
 [1] "2010-01-04" "2010-02-01" "2010-03-01" "2010-04-05" "2010-05-03"
 [6] "2010-06-07" "2010-07-05" "2010-08-02" "2010-09-06" "2010-10-04"
[11] "2010-11-01" "2010-12-06" "2011-01-03" "2011-02-07" "2011-03-07"
[16] "2011-04-04" "2011-05-02" "2011-06-06" "2011-07-04" "2011-08-01"
[21] "2011-09-05" "2011-10-03" "2011-11-07" "2011-12-05" "2012-01-02"
[26] "2012-02-06" "2012-03-05" "2012-04-02" "2012-05-07" "2012-06-04"
[31] "2012-07-02" "2012-08-06" "2012-09-03" "2012-10-01" "2012-11-05"
[36] "2012-12-03" "2013-01-07" "2013-02-04" "2013-03-04" "2013-04-01"
[41] "2013-05-06" "2013-06-03" "2013-07-01" "2013-08-05" "2013-09-02"
[46] "2013-10-07" "2013-11-04" "2013-12-02" "2014-01-06" "2014-02-03"
[51] "2014-03-03" "2014-04-07" "2014-05-05" "2014-06-02" "2014-07-07"
[56] "2014-08-04" "2014-09-01" "2014-10-06" "2014-11-03" "2014-12-01"
[61] "2015-01-05" "2015-02-02" "2015-03-02" "2015-04-06" "2015-05-04"
[66] "2015-06-01" "2015-07-06" "2015-08-03" "2015-09-07" "2015-10-05"
[71] "2015-11-02" "2015-12-07"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接