我有兩個日期,需要知道有多少星期一,星期二,星期三,等它們之間,用R之間特定的工作日數下面是一個僞代碼的方法:R:兩個日期
#PSEUDOCODE
countwd <- function(startdate, enddate, weekday)
例
>countwd("2014-01-01", "2014-03-30", "Monday")
[1] 13
是否有一個現有的包/功能呢?如果不是,這個功能怎麼設置?
我有兩個日期,需要知道有多少星期一,星期二,星期三,等它們之間,用R之間特定的工作日數下面是一個僞代碼的方法:R:兩個日期
#PSEUDOCODE
countwd <- function(startdate, enddate, weekday)
例
>countwd("2014-01-01", "2014-03-30", "Monday")
[1] 13
是否有一個現有的包/功能呢?如果不是,這個功能怎麼設置?
一個R函數
weekdays
返回日期的星期,即
countwd <- function(startdate, enddate, weekday){
x <- seq(startdate, enddate, by=1)
y <- weekdays(x)
sum(y == weekday)
}
你可以使用這樣的事情...
$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"
}
錯誤的語言。 – Roland 2014-10-16 12:29:55
這是繼本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
但不要忘了平日的輸出取決於語言環境。 – Roland 2014-10-16 12:07:40
這工作正常。有趣的是看到一個更有效的變體,它計算出對應於開始和結束日的平日,並進行適當的計算(每個工作日+數字爲7 *)。 – 2014-10-16 12:12:29
@BenBolker查看我的答案。您可能會節省幾微秒。 – Roland 2014-10-16 12:30:49