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
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.