[R] Find out the day of week for a chron object?

Gabor Grothendieck ggrothendieck at myway.com
Thu Mar 4 07:09:08 CET 2004



You can avoid the loop in your calculation.  Since Friday is
day of the week 5, if the day of the week d of chron date x
is greater than 5 then Friday was d-5 days ago; otherwise, if d-5 is 
zero or negative then we have to add 7 to it to ensure that its 
in the past.  Thus:

prevFriday <- function(x) {
	d <- with(month.day.year(x), day.of.week(month,day,year)) 
	x - ifelse( d-5>0, d-5, d-5+7 )
}

Date:   Thu, 4 Mar 2004 00:03:59 +0530 
From:   Ajay Shah <ajayshah at mayin.org>
To:   Gabor Grothendieck <ggrothendieck at myway.com> 
Cc:   <r-help at stat.math.ethz.ch> 
Subject:   Re: [R] Find out the day of week for a chron object? 

 
On Wed, Mar 03, 2004 at 06:58:02AM -0500, Gabor Grothendieck wrote:
> 
> Here are three different ways (using x as defined in your 
> post):
> 
> with( month.day.year(x), day.of.week(month,day,year) )
> 
> do.call( "day.of.week", month.day.year(x) )
> 
> as.numeric(x-3)%%7 # uses fact that chron(3) is Sunday

Thanks! Using this, I wrote --

library(chron);
prevFriday <- function(x) {
repeat {
x <- x - 1;
if (5 == with(month.day.year(x), day.of.week(month,day,year))) break;
}
return(x);
}
x = dates("12-02-04", format="d-m-y")
print(prevFriday(x))

and it works. :-)

Could someone give me a glimmer into HOW and WHY that expression 
with(month.day.year(x), day.of.week(month,day,year))
works? :-)

-- 
Ajay Shah Consultant
ajayshah at mayin.org Department of Economic Affairs
http://www.mayin.org/ajayshah Ministry of Finance, New Delhi




More information about the R-help mailing list