R:两个日期之间的特定工作日数

时间:2014-10-16 11:57:50

标签: r date weekday

我有两个约会,需要知道他们之间有多少星期一,星期二,星期三等,使用R.这是一种假代码方法:

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

实施例

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

[1] 13

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

3 个答案:

答案 0 :(得分:5)

R功能

weekdays

返回日期的工作日,即

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

答案 1 :(得分:1)

这符合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

答案 2 :(得分:-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"
}