Calculate the number of weekdays between 2 dates in R

前端 未结 6 1013
北海茫月
北海茫月 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:50

    I use the following approach - first a helper:

    weekDays <- function(UPPER = TRUE) {
        days <- c('MONDAY', 'TUESDAY', 'WEDNESDAY',
          'THURSDAY', 'FRIDAY', 'SATURDAY', 
          'SUNDAY')
        if(!UPPER) return(.Internal(tolower(days))) 
        days
    }
    

    ... and now the main function:

    NumWeekDays <- function(dd, Xdays = c('saturday', 'sunday')) {
        # a function to count the number of non-Xdays in a month
        # >
        # first check if Xdays is of correct format
        stopifnot( all(.Internal(tolower(Xdays)) %in% weekDays(UP = FALSE)))
        # >
        # a helper function to find the number of non-X days between two dates
        NonXDays <- function(startDate, endDate, Xdays) {
            sum(!(.Internal(tolower(weekdays(seq(startDate, endDate, 'day')))) %in% 
                  .Internal(tolower(Xdays))))
        }
        startDate <- as.Date(as.yearmon(index(dd)), frac = 0)
        endDate <- as.Date(as.yearmon(index(dd)), frac = 1)
        vapply(1:nrow(dd), 
               FUN = function(i) NonXDays(startDate[i], 
                                          endDate[i], 
                                          Xdays = c('saturday', 'sunday')), 
               FUN.VALUE = numeric(1))
    }
    

    Example:

    set.seed(1)
    dx <- apply.monthly(xts(rnorm(600), order.by = Sys.Date() + 1:600), mean)
    
    R> NumWeekDays(dx)
     [1] 23 21 22 23 20 23 22 20 22 22 21 22 23 21 22 22 21 23 21 21
    

提交回复
热议问题