r - Finding the third Friday of a month and data table -
i want find third friday of month delivery date of futures, used solution here, getnthdayofweek
rcppbdt
package:
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)]
however message: error: expecting single value
. missing?
since did not specify by
clause in transformation, :=
(presumably) trying apply getnthdayofweek
vectorized function.
this should work:
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
or, more generally, in case have duplicate mon,year
tuples in object:
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
Comments
Post a Comment