Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
850 views
in Technique[技术] by (71.8m points)

add 1 business day to date in R

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?

Example:

mydate = as.Date("2013-12-24")
mydate + 1 #this is a holiday so I want this to roll over to the 26th instead
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...