Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Similar to this question. Thanks!

/edit: @J. Winchester's answer is great, but I was wondering if anyone could think of a way to vectorize this, so that it'll work on 2 columns of dates. Thanks! /edit 2: Thanks again!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
782 views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...