在R中添加1个工作日 [英] add 1 business day to date in R

查看:156
本文介绍了在R中添加1个工作日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Date object in R and would like to add 1 business day to this date. If the result is a holiday, I would like the date to be incremented to the next non-holiday date. Let's assume I mean NYSE holidays. How can I do this?

示例:

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() code> roll = -Inf 设置 data.table 查找日历,如下所示:

I might use a combo of timeDate::nextBizDay() and roll=-Inf to set up a data.table lookup calendar, like this:

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中添加1个工作日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆