我在R中有一个Date对象,想在此日期前添加1个工作日。如果结果是假日,我希望将日期增加到下一个非假日日期。假设我的意思是纽约证券交易所假期。我怎样才能做到这一点?

例子:

mydate = as.Date("2013-12-24")
mydate + 1 #this is a holiday so I want this to roll over to the 26th instead

最佳答案

我可能会使用timeDate::nextBizDay()roll=-Inf的组合来设置data.table查找日历,如下所示:

library(data.table)
library(timeDate)

## Set up a calendar for 2013 & 2014
cal <- data.table(date=seq(from=as.Date("2013-01-01"), by=1, length=730),
                  key="date")
cal2 <- copy(cal)
cal2[,nextBizDay:=date+1]
cal2 <- cal2[isBizday(as.timeDate(nextBizDay)),]
cal <- cal2[cal,,roll=-Inf]

## Check that it works
x <- as.Date("2013-12-21")+1:10
cal[J(x),]
#           date nextBizDay
#  1: 2013-12-22 2013-12-23
#  2: 2013-12-23 2013-12-24
#  3: 2013-12-24 2013-12-26
#  4: 2013-12-25 2013-12-26
#  5: 2013-12-26 2013-12-27
#  6: 2013-12-27 2013-12-30
#  7: 2013-12-28 2013-12-30
#  8: 2013-12-29 2013-12-30
#  9: 2013-12-30 2013-12-31
# 10: 2013-12-31 2014-01-01

## Or perhaps:

lu <- with(cal, setNames(nextBizDay, date))
lu[as.character(x[1:6])]
#   2013-12-22   2013-12-23   2013-12-24   2013-12-25   2013-12-26   2013-12-27
# "2013-12-23" "2013-12-24" "2013-12-26" "2013-12-26" "2013-12-27" "2013-12-30"

关于r - 迄今在R中添加1个工作日,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20709654/

10-12 20:33