2013-03-18 40 views
1

我需要知道给定月份的第一个工作日,R中是否有包含相关函数的包?访问月份的第一个工作日

+0

你说的经营业务一天是什么意思?哪个日历? – agstudy 2013-03-18 13:52:49

+0

说例如英国日历... – 2013-03-18 14:06:27

+0

不要说,例如,如果你想要的只是每个月的第一个星期一! – 2013-03-18 14:15:31

回答

7

TIMEDATE包有一个功能isBizday,这将帮助你在这里。将会有更优雅的方式将dateTime对象转换为其他格式,但这至少应该让你开始。

library(timeDate) 

## Example data 
dates <- as.Date("2013-01-01") + 0:364 
Dates <- as.timeDate(dates) 

## Extract the first business day of each month 
bizDates <- dates[isBizday(Dates, holidays=holidayLONDON())] 
firsts <- tapply(bizdates, months(bizdates), min) 
sapply(firsts, function(X) as.character(as.Date(X))) 
#   1   2   3   4   5   6 
# "2013-01-02" "2013-02-01" "2013-03-01" "2013-04-01" "2013-05-01" "2013-06-03" 
#   7   8   9   10   11   12 
# "2013-07-01" "2013-08-01" "2013-09-03" "2013-10-01" "2013-11-01" "2013-12-02" 
5

假设你想,是不是星期六或星期日每月的第一天:

businessDay<-function(month,year){ 
    #3 first dates of the month is sufficient 
    d <- as.POSIXlt(paste(year,month,1:3,sep="-")) 
    #POSIXlt object contains the info about the weekday as number 0-6 (starting Sunday) 
    d[which(d$wday>0 & d$wday<6)[1]] 
} 

businessDay(3,2013) 
[1] "2013-03-01" 

或者,如果你要想在一天的名称:

businessDay<-function(month,year){ 
    d <- as.POSIXlt(paste(year,month,1:3,sep="-")) 
    weekdays(d[which(d$wday>0 & d$wday<6)[1]]) 
} 

businessDay(1,2013) 
[1] "friday" 
5

您可以使用isBusinessDayRQuantLib,它检查是否有一天被赋予了日历busniess一天。一种想法是给一个月的第一天,并采取分busniess日

例如这里2009年4月的第一个工作日是:

library(RQuantLib) 
dates <- seq(from=as.Date("2009-04-01"), to=as.Date("2009-04-05"), by=1) 
min(dates[isBusinessDay("UnitedKingdom", dates)]) 
"2009-04-01" 
相关问题