【问题标题】:Fill a vector with weekdays only仅用工作日填充向量
【发布时间】:2013-02-14 21:27:05
【问题描述】:

我知道开始日期start 和最后日期maturity。如何在不考虑周末日期的情况下填写带有日期的向量? 例如,假设:

> start = as.Date("2013-02-28");
> maturity = as.Date("2013-03-07");

我想得到以下向量作为结果:

results
[1] "2013-03-01" "2013-03-04" "2013-03-05" "2013-03-06" "2013-03-07"



> start = as.Date("2013-02-28");
> maturity = as.Date("2013-03-07");
> x <- seq(start,maturity,by = 1)
> x
[1] "2013-02-28" "2013-03-01" "2013-03-02" "2013-03-03" "2013-03-04" "2013-03-05"
[7] "2013-03-06" "2013-03-07"
> x <- x[!weekdays(x) %in% c('Saturday','Sunday')]
> x
[1] "2013-02-28" "2013-03-01" "2013-03-02" "2013-03-03" "2013-03-04" "2013-03-05"
[7] "2013-03-06" "2013-03-07"

同样的结果...?

【问题讨论】:

    标签: r date vector


    【解决方案1】:

    可能有十亿种方法可以使用来自多个包的各种功能来做到这一点。但我的第一个想法是简单地制作一个序列,然后删除周末:

    x <- seq(as.Date('2011-01-01'),as.Date('2011-12-31'),by = 1)
    x <- x[!weekdays(x) %in% c('Saturday','Sunday')]
    

    此答案仅对基于英语的系统有效。例如,在法语版本中,“Saturday”和“Sunday”必须翻译成“samedi”和“dimanche”

    【讨论】:

      【解决方案2】:

      这比@joran 的回答更人性化:) ,但它不依赖于本地时间

      dd <- seq(as.Date('2011-01-01'),as.Date('2011-12-31'),by = 1)
      dd[! (as.POSIXlt(dd)$wd %in% c(0,1))]
      

      PS:另一种选择,是在应用weekdays之前设置本地人

      tt <- Sys.getlocale('LC_TIME')
      Sys.setlocale('LC_TIME','ENGLISH')
      dd <- dd[!weekdays(x) %in% c('Saturday','Sunday')]
      Sys.setlocale('LC_TIME',tt)
      

      【讨论】:

        猜你喜欢
        • 2018-10-20
        • 2012-09-29
        • 2020-07-07
        • 1970-01-01
        • 2017-01-07
        • 1970-01-01
        • 2019-09-03
        • 2020-05-29
        • 2018-07-10
        相关资源
        最近更新 更多