查找一个月的第三个星期五和数据表

时间:2016-01-28 17:11:17

标签: r data.table

我想找到期货交割日期的一个月的第三个星期五,我使用了来自getNthDayOfWeek包的解决方案hereRcppBDT

library(data.table)
library(RcppBDT)

data <- setDT(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))))
data[, third.friday:= getNthDayOfWeek(third, Fri, mon, year)]

但是我收到此消息:Error: expecting a single value。我错过了什么?

1 个答案:

答案 0 :(得分:4)

由于您未在转换中指定by子句,:=(大概)会尝试将getNthDayOfWeek应用为向量化函数。

这应该有效:

Data[
  ,third.friday := getNthDayOfWeek(third, Fri, mon, year)
  ,by = "mon,year"]
Data
#   mon year third.friday
#1:   5 2011   2011-05-20
#2:   6 2011   2011-06-17
#3:   7 2011   2011-07-15
#4:   8 2011   2011-08-19
#5:   9 2011   2011-09-16
#6:  10 2011   2011-10-21
#7:  11 2011   2011-11-18
#8:  12 2011   2011-12-16
#9:   1 2012   2012-01-20

或者,更一般地说,如果您的对象中有重复的mon,year元组:

Data[,Idx := 1:.N][
  ,third.friday := getNthDayOfWeek(third, Fri, mon, year)
  ,by = "mon,year,Idx"
][,Idx := NULL][]
#   mon year third.friday
#1:   5 2011   2011-05-20
#2:   6 2011   2011-06-17
#3:   7 2011   2011-07-15
#4:   8 2011   2011-08-19
#5:   9 2011   2011-09-16
#6:  10 2011   2011-10-21
#7:  11 2011   2011-11-18
#8:  12 2011   2011-12-16
#9:   1 2012   2012-01-20