Calculate the number of weekdays between 2 dates in R

前端 未结 6 1027
北海茫月
北海茫月 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条回答
  •  感动是毒
    2020-11-29 03:43

    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.

    Edit:

    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?)

提交回复
热议问题