R: finding difference in business days

前端 未结 1 482
后悔当初
后悔当初 2021-01-23 23:29

Having problem calculating the date difference in business days, i.e. exclude weekends like networkdays function in Excel.

Here is my data.

e <- struc         


        
相关标签:
1条回答
  • 2021-01-24 00:15

    Nweekdays() function is adapted from @J. Won. solution at Calculate the number of weekdays between 2 dates in R

    This modified function takes into account of date differences of either positive or negative, whereas the above link has accepted solution for positive date difference.

    library("dplyr")
    
    e2 <- structure(list(date.pr = structure(c(16524, 16524, 16507, 16510, 16510, 16524, 16510, 5974), class = "Date"), 
                         date.po = structure(c(16524, 16525, 16510, 16517, 16524, 16510, 16531, 15974), class = "Date")), 
                    .Names = c("date.1", "date.2"), class = c("tbl_df", "data.frame"), row.names = c(NA, -8L))
    
    Nweekdays <- Vectorize(
      function(a, b) 
      {
        ifelse(a < b, 
               return(sum(!weekdays(seq(a, b, "days")) %in% c("Saturday", "Sunday")) - 1), 
               return(sum(!weekdays(seq(b, a, "days")) %in% c("Saturday", "Sunday")) - 1))
      })
    
    
    > e2 %>%
         mutate(wkd1 = format(date.1, "%A"),
                wkd2 = format(date.2, "%A"),
                ndays_with_wkends = ifelse((date.2 > date.1), (date.2 - date.1), (date.1 - date.2)), 
                ndays_no_wkends = Nweekdays(date.1, date.2))
    
    Source: local data frame [8 x 6]
    
          date.1     date.2   wkd1     wkd2 ndays_with_wkends ndays_no_wkends
          (date)     (date)  (chr)    (chr)             (dbl)           (dbl)
    1 2015-03-30 2015-03-30 Monday   Monday                 0               0
    2 2015-03-30 2015-03-31 Monday  Tuesday                 1               1
    3 2015-03-13 2015-03-16 Friday   Monday                 3               1
    4 2015-03-16 2015-03-23 Monday   Monday                 7               5
    5 2015-03-16 2015-03-30 Monday   Monday                14              10
    6 2015-03-30 2015-03-16 Monday   Monday                14              10
    7 2015-03-16 2015-04-06 Monday   Monday                21              15
    8 1986-05-11 2013-09-26 Sunday Thursday             10000            7143
    
    > e2 %>% mutate(ndays_no_wkends = Nweekdays(date.1, date.2))
    
    Source: local data frame [8 x 3]
    
          date.1     date.2 ndays_no_wkends
          (date)     (date)           (dbl)
    1 2015-03-30 2015-03-30               0
    2 2015-03-30 2015-03-31               1
    3 2015-03-13 2015-03-16               1
    4 2015-03-16 2015-03-23               5
    5 2015-03-16 2015-03-30              10
    6 2015-03-30 2015-03-16              10
    7 2015-03-16 2015-04-06              15
    8 1986-05-11 2013-09-26            7143
    
    0 讨论(0)
提交回复
热议问题