仅在工作日填充矢量

时间:2013-02-28 15:48:12

标签: r date vector

我知道开始日期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"

结果相同......?

2 个答案:

答案 0 :(得分:8)

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

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

此答案仅适用于基于英语的系统。例如,在法语版本中,“星期六”和“星期日”必须翻译成“samedi”和“dimanche”

答案 1 :(得分:4)

这比@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)