我试图弄清楚过去3年如何创建一个月的第三个星期五的日期向量
先谢谢你
答案 0 :(得分:15)
RcppBDT包裹包含了Boost Date_Time的一些日期(和相关时间)计算。
其中有一个函数在这里做你想做的事情:
R> getNthDayOfWeek(third, Fri, Apr, 2014)
[1] "2014-04-18"
R>
而不是(package-local)常量Jan,Feb,...你也可以使用整数来填充你的第六个月。
以下是序列的简单(丑陋)黑客攻击:
R> dates <- data.frame(mon=c(5:12, 1:12, 1:12, 1:4),
+ year=c(rep(2011,8), rep(2012,12),
+ rep(2013,12), rep(2014,4)))
R> sapply(1:36, function(i)
+ format(getNthDayOfWeek(third, Fri, dates[i,1], dates[i,2])))
[1] "2011-05-20" "2011-06-17" "2011-07-15" "2011-08-19"
[5] "2011-09-16" "2011-10-21" "2011-11-18" "2011-12-16"
[9] "2012-01-20" "2012-02-17" "2012-03-16" "2012-04-20"
[13] "2012-05-18" "2012-06-15" "2012-07-20" "2012-08-17"
[17] "2012-09-21" "2012-10-19" "2012-11-16" "2012-12-21"
[21] "2013-01-18" "2013-02-15" "2013-03-15" "2013-04-19"
[25] "2013-05-17" "2013-06-21" "2013-07-19" "2013-08-16"
[29] "2013-09-20" "2013-10-18" "2013-11-15" "2013-12-20"
[33] "2014-01-17" "2014-02-21" "2014-03-21" "2014-04-18"
R>
请注意,我使用format()
转换为字符;否则日期变成数字。这只是sapply()
的副作用,你也可以这样做。将Date
类型分配回我们在此处使用的数据框dates
。
答案 1 :(得分:6)
timeDate
包有一些非常相似的内容:
library(timeDate)
tS = timeSequence(from = "2010-01-01", to = "2013-12-31", by = "month")
timeNthNdayInMonth(tS, nday = 5, nth = 3, format = "%Y-%m-%d")
## GMT
## [1] [2010-01-15] [2010-02-19] [2010-03-19] [2010-04-16] [2010-05-21] [2010-06-18] [2010-07-16]
## [8] [2010-08-20] [2010-09-17] [2010-10-15] [2010-11-19] [2010-12-17] [2011-01-21] [2011-02-18]
## [15] [2011-03-18] [2011-04-15] [2011-05-20] [2011-06-17] [2011-07-15] [2011-08-19] [2011-09-16]
## [22] [2011-10-21] [2011-11-18] [2011-12-16] [2012-01-20] [2012-02-17] [2012-03-16] [2012-04-20]
## [29] [2012-05-18] [2012-06-15] [2012-07-20] [2012-08-17] [2012-09-21] [2012-10-19] [2012-11-16]
## [36] [2012-12-21] [2013-01-18] [2013-02-15] [2013-03-15] [2013-04-19] [2013-05-17] [2013-06-21]
## [43] [2013-07-19] [2013-08-16] [2013-09-20] [2013-10-18] [2013-11-15] [2013-12-20]
答案 2 :(得分:5)
替代基础解决方案再次使用@jbaums数据提供相同的结果:
d <- seq(as.Date("2000/1/1"), by = 1, length.out = 500)
d <- as.POSIXlt(d)
d <- d[d$wday==5]
as.Date(d[ave(d$mon,list(d$mon,d$year),FUN=seq_along)==3])
答案 3 :(得分:3)
要完善它,使用base
函数执行此操作是一种混乱的方式:
d <- seq(as.Date("2000/1/1"), by = 1, length.out = 500)
sort(as.Date(tapply(d[which(format(d, '%a')=='Fri')],
format(d[which(format(d, '%a')=='Fri')], '%m-%Y'),
function(x) x[3]), origin='1970-01-01'))