Calculate the number of weekdays between 2 dates in R

前端 未结 6 1015
北海茫月
北海茫月 2020-11-29 02:59

I\'m trying to write an R function to calculate the number of weekdays between two dates. For example, Nweekdays(\'01/30/2011\',\'02/04/2011\') would equal 5.

Simila

6条回答
  •  Happy的楠姐
    2020-11-29 03:49

    J. Win.'s answer is good, but can be quite a bit faster with lubridate.

    require(lubridate)
    count_weekdays<- Vectorize(function(from,to) sum(!wday(seq(from, to, "days")) %in% c(1,7)))
    
    

    Here are time results from my machine:

    > v1<- seq(from = ymd(19000101), to = ymd(20000101), by='month')
    > v2<- seq(from = ymd(20000101), to = ymd(21000101), by='month')
    
    > require(tictoc)
    
    > tic(); out<- Nweekdays(v1,v2); toc();
    293.06 sec elapsed
    
    > tic(); out<- count_weekdays(v1,v2); toc();
    9.95 sec elapsed
    
    

    About 30x faster. Meaningful if your doing a lot of periods.

提交回复
热议问题