Calculate the number of weekdays between 2 dates in R

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

    Date1 <- as.Date("2011-01-30")
    Date2 <- as.Date("2011-02-04")    
    sum(!weekdays(seq(Date1, Date2, "days")) %in% c("Saturday", "Sunday"))
    

    EDIT: And Zach said, let there be Vectorize :)

    Dates1 <- as.Date("2011-01-30") + rep(0, 10)
    Dates2 <- as.Date("2011-02-04") + seq(0, 9)
    Nweekdays <- Vectorize(function(a, b) 
      sum(!weekdays(seq(a, b, "days")) %in% c("Saturday", "Sunday")))
    Nweekdays(Dates1, Dates2)
    

提交回复
热议问题