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
I wrote this one, but the other answer is better :)
Nweekdays <- function(a,b)
{
dates <- as.Date(as.Date(a,"%m/%d/%y",origin="1900-01-01"):as.Date(b,"%m/%d/%y",origin="1900-01-01"),origin="1900-01-01")
days <- format(dates,"%w")[c(-1,-length(dates))]
return(sum(!days%in%c(0,6)))
}
Nweekdays('01/30/2011','02/04/2011')
[1] 3
EDIT: Calculates how many weekdays are in between of the two specified days.
Taking J. Winchesters advice, the function could be streamlined as:
Nweekdays <- function(a,b)
{
dates <- as.numeric((as.Date(a,"%m/%d/%y")):(as.Date(b,"%m/%d/%y")))
dates <- dates[- c(1,length(dates))]
return(sum(!dates%%7%in%c(0,6)))
}
Some results:
> Nweekdays('01/30/2011','02/04/2011')
[1] 4
>
> Nweekdays('01/30/2011','01/30/2011')
[1] 0
>
> Nweekdays('01/30/2011','01/25/2011')
[1] 3
Note that this is locale independent. (On that topic, how do I change locale anyway?)