2014-10-16 65 views
0

我有两个日期,需要知道有多少星期一,星期二,星期三,等它们之间,用R之间特定的工作日数下面是一个伪代码的方法:R:两个日期

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

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

[1] 13 

是否有一个现有的包/功能呢?如果不是,这个功能怎么设置?

回答

5

一个R函数

weekdays 

返回日期的星期,即

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

但不要忘了平日的输出取决于语言环境。 – Roland 2014-10-16 12:07:40

+0

这工作正常。有趣的是看到一个更有效的变体,它计算出对应于开始和结束日的平日,并进行适当的计算(每个工作日+数字为7 *)。 – 2014-10-16 12:12:29

+0

@BenBolker查看我的答案。您可能会节省几微秒。 – Roland 2014-10-16 12:30:49

-2

你可以使用这样的事情...

$startTime = strtotime('2011-12-12'); 
$endTime = strtotime('2012-02-01'); 

$weeks = array(); 

while ($startTime < $endTime) { 
    $weeks[] = date('W', $startTime); 
    $startTime += strtotime('+1 week', 0); 
} 

var_dump($weeks); 

你会得到如下所示的结果:

array(8) { 
    [0]=> 
    string(2) "50" 
    [1]=> 
    string(2) "51" 
    [2]=> 
    string(2) "52" 
    [3]=> 
    string(2) "01" 
    [4]=> 
    string(2) "02" 
    [5]=> 
    string(2) "03" 
    [6]=> 
    string(2) "04" 
    [7]=> 
    string(2) "05" 
} 
+1

错误的语言。 – Roland 2014-10-16 12:29:55

1

这是继本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