Skip to content

Weekdays

2 messages · Whit Armstrong, Thomas Lumley

#
Hello,

I'm trying to write a function that returns the number of weekdays between a
vector of start dates and a vector of end dates.

Subtracting the 2 times the number of whole weeks is the easy part and works
if the number of days is a multiple of 7.

However, the number of weekend days in the tail is a little harder.  It
depends on both the start date of the tail and the number of days in the
tail.

Any suggestions for a more elegant solution would be helpful.

Thanks,
Whit Armstrong

bdays <- function(sdate,edate)
{
	sdate <- as.POSIXlt(sdate)
	edate <- as.POSIXlt(edate)

	length <- as.integer(difftime(edate,sdate))

	weeks <- floor(length/7)
	tail <- length%%7

	# true no matter what day of the week the start date is
	weekend.days <- weeks*2

	weekend.days <- weekend.days + # number of weekend days in tail

	length-weekend.days
}



-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
#
On Fri, 22 Feb 2002, Whit Armstrong wrote:

            
Well, an efficient brute-force solution is a lookup table.

The weekdays() function returns the day of the week, and so you can
construct a 7x7 table of tail lengths and do

   tail<-tailtable[weekdays(start),weekdays(end)]

I don't know if this counts as elegant.

	-thomas



-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._