2

我需要知道给定月份的第一个工作日,R 中是否有一些包含相关功能的包?

4

3 回答 3

8

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" 
于 2013-03-18T14:12:16.477 回答
6

假设您想要该月的第一天不是星期六或星期日:

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"
于 2013-03-18T14:07:23.550 回答
6

您可以使用isBusinessDay from RQuantLib,它检查一天是否是给定日历的工作日。一个想法是给一个月的第一天,并采取最小的工作日

例如,这里 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"
于 2013-03-18T14:13:21.910 回答