【问题标题】:R: Number of specific weekdays between two datesR:两个日期之间的特定工作日数
【发布时间】:2014-12-11 18:49:43
【问题描述】:

我有两个日期,需要知道它们之间有多少个星期一、星期二、星期三等,使用 R。这是一种伪代码方法:

#PSEUDOCODE    
countwd <- function(startdate, enddate, weekday)

例子

>countwd("2014-01-01", "2014-03-30", "Monday")

[1] 13

是否有用于此的现有包/功能?如果没有,如何设置此功能?

【问题讨论】:

    标签: r date weekday


    【解决方案1】:

    R函数

    weekdays
    

    返回日期的工作日,即

    countwd <- function(startdate, enddate, weekday){
        x <- seq( startdate, enddate, by=1 )
        y <- weekdays( x )
        sum( y == weekday )
    }
    

    【讨论】:

    • 但不要忘记工作日的输出取决于语言环境。
    • 这很好用。看到一个更有效的变体会很有趣,它计算出对应于开始和结束日期的工作日并进行适当的(7*每个工作日+剩余的数字)计算。
    • @BenBolker 查看我的回答。您可能会节省一些微秒。
    【解决方案2】:

    这遵循 Ben Bolker 的建议:

    sapply(weekdays(as.Date("2014-01-01")+1:7), function(x) countwd(as.Date("2014-01-01"), as.Date("2014-03-30"), x))
    #Donnerstag    Freitag    Samstag    Sonntag     Montag   Dienstag   Mittwoch 
    #        13         13         13         13         12         12         13 
    
    countwd2 <- function(startdate, enddate, weekday){
      d <- as.integer(enddate - startdate) + 1
      d %/% 7 +
        (weekday %in% weekdays(seq(startdate, length.out=d %% 7, by=1)))
    }
    
    sapply(weekdays(as.Date("2014-01-01")+1:7), function(x) countwd2(as.Date("2014-01-01"), as.Date("2014-03-30"), x))
    #Donnerstag    Freitag    Samstag    Sonntag     Montag   Dienstag   Mittwoch 
    #        13         13         13         13         12         12         13 
    
    library(microbenchmark)
    microbenchmark(countwd(as.Date("2014-01-01"), as.Date("2014-03-30"), "Montag"),
                   countwd2(as.Date("2014-01-01"), as.Date("2014-03-30"), "Montag"))
    
    #Unit: microseconds
    #                                                            expr     min       lq     mean   median       uq      max neval cld
    # countwd(as.Date("2014-01-01"), as.Date("2014-03-30"), "Montag") 618.093 636.1095 691.7498 652.2770 682.4585 2164.709   100   b
    #countwd2(as.Date("2014-01-01"), as.Date("2014-03-30"), "Montag") 454.870 476.2740 504.2249 495.5215 528.9370  659.668   100  a
    

    较长时间的基准:

    #Unit: microseconds
    #                                                             expr       min        lq       mean     median        uq       max neval
    #  countwd(as.Date("2014-01-01"), as.Date("2054-03-30"), "Montag") 41384.146 42110.334 44212.9498 42896.7305 43281.538 92393.218   100
    # countwd2(as.Date("2014-01-01"), as.Date("2054-03-30"), "Montag")   445.323   466.265   567.4693   586.6805   652.432   822.276   100
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-20
      • 2019-02-24
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 1970-01-01
      相关资源
      最近更新 更多