【问题标题】:Accessing the first business day of a Month访问一个月的第一个工作日
【发布时间】:2013-03-06 21:05:47
【问题描述】:

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

【问题讨论】:

  • 工作日是什么意思?哪个日历?
  • 比如说英国日历...
  • 不要这么说,例如,如果你只想每个月的第一个星期一!
  • @JoshO'Brien 我认为他的意思是他希望本月的第一天不在周末。幸运的是我的英语和问题一样糟糕:)
  • @LorenzoRigamonti 您能否编辑您的问题并准确说明您所说的商务日是什么意思……我认为您的意思是开放日。至少根据接受的答案..

标签: r date time-series


【解决方案1】:

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" 

【讨论】:

    【解决方案2】:

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

    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"
    

    【讨论】:

      【解决方案3】:

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

      例如,这里 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"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-22
        相关资源
        最近更新 更多