如何从2010-01-01到2015-12-31提取每个月的第一个星期一?
答案 0 :(得分:12)
我们可以使用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"
答案 1 :(得分:5)
另一个评论:使用Boost Date_Time库:
SELECT * FROM scores ORDER BY high_score DESC
答案 2 :(得分:4)
这是基础R解决方案。它只需要三行代码。在zoo quickref vignette中,有一个单行函数nextfri
,用于在给定日期或之后的下一个星期五。如果我们在该函数的主体中用1(星期一)替换每个5(星期五),我们在给定日期或之后的下一个星期一。 (那里的公式不包括这里使用的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"