From ggrothendieck at gmail.com  Tue Sep 18 03:13:08 2007
From: ggrothendieck at gmail.com (Gabor Grothendieck)
Date: Mon, 17 Sep 2007 21:13:08 -0400
Subject: [Rd] Date vs date (long)
In-Reply-To: <200709172111.l8HLBsF24362@hsrnfs-101.mayo.edu>
References: <200709172111.l8HLBsF24362@hsrnfs-101.mayo.edu>
Message-ID: <971536df0709171813g3d39e4efif10b8b771a3b1f3d@mail.gmail.com>

On 9/17/07, Terry Therneau <therneau at mayo.edu> wrote:
> Gabor Grothendieck
>
> as.Date(10)
> You can define as.Date.numeric in your package and then it will work.  zoo
> has done that.
>
> library(zoo)
> as.Date(10)
>
>  This is also a nice idea.  Although adding to a package is possible, it is
> now very hard to take away, given namespaces.  That is, I can't define my
> own Math.Date to do away with the creation of timespan objects.  Am I
> correct?  Is it also true that adding methods is hard if one uses version 4
> classes?
>
>  The rest of Gabor's comments are workarounds for the problem I raised.
> But I don't want to have to wrap "as.numeric" around all of my date
> calculations.

You can define as.Date.numeric and Ops.Date, say, using S3 and these
will be added to the whatever is there but won't override the existing
+.Date and -.Date nor would you want them to or else the behavior would
be different depending on whether your package was there or not.  Also
namespaces should not be a problem since zoo uses namespaces and
it defined its own as.Date.numeric.

Try this:

Ops.Date <- function (e1, e2) {
    e <- if (missing(e2)) {
        NextMethod(.Generic)
    }
    else if (any(nchar(.Method) == 0)) {
        NextMethod(.Generic)
    }
    else {
        e1 <- as.numeric(e1)
	e2 <- as.numeric(e2)
        NextMethod(.Generic)
    }
    e
}

Sys.Date() / Sys.Date()
Sys.Date() + as.numeric(Sys.Date())
as.numeric(Sys.Date()) + as.numeric(Sys.Date())

Sys.Date() + Sys.Date() # error since its intercepted by +.Date

Thus you will have to issue some as.numeric calls but perhaps not too
many.

However, I think its better not to implement Ops.Date as above but
just leave the Date operations the way they are, extend it with
as.Date.numeric like zoo has done and force the user to use as.numeric
in other cases to make it clear from the code that  there is conversion
going on.  I have done a fair amount of Date manipulation and have not
found the as.numeric to be onerous.



[Rd] Date vs date (long)
Gabor Grothendieck