Daniel Murphy
2010-Jun-09 16:21 UTC
[Rd] Extract/format/show for S4 objects (Johann Hibschman)
Johann, Following up on Gabor's reply, the mondate package (new on CRAN last week) will accomplish your needs.>I'm trying to make an integer-backed quarter (as in fraction of year) >class, but I can't quite it to work. I want integer-backed so I don't >have to worry about floating-point effects when doing math, and so that >I can use it as in data.table.mondate represents a date internally as a numeric, not an integer, but the integer part corresponds to months, not years, so a zero fractional part of a mondate corresponds to a "complete month." Every third whole number, therefore, would correspond to a complete quarter. Arithmetic in months (or quarters by dividing by 3) returns a numeric with a "timeunits" attribute. mondate's can be stored in a data.frame.> (A<-mondate.ymd(2010,3*(1:4))) # display format is "U.S.", my locationmondate: timeunits="months" [1] 03/31/2010 06/30/2010 09/30/2010 12/31/2010> diff(A) # 3 months apart[1] 3 3 3> A-mondate("12/31/2009") # months since the end of last year; dateinput format also works for my location [1] 3 6 9 12 attr(,"timeunits") [1] "months"> c((A-mondate("12/31/2009"))/3) # divide by 3 and remove the attribute andyou have quarters [1] 1 2 3 4> data.frame(QtrEnd=A, Amount=rep(1000,4))QtrEnd Amount 1 03/31/2010 1000 2 06/30/2010 1000 3 09/30/2010 1000 4 12/31/2010 1000 If the date you are subtracting off is somewhere in the fourth quarter of 2009 but you still want to treat it as being representative of the fourth quarter, the floor function will remove the fractional part of the difference in quarters (I will enter November 1st in non-US format):> floor(c((A-mondate("2009-11-1"))/3))[1] 1 2 3 4>First of all, is there a good reference for this anywhere? All of the >S4 tutorials that I've found have been too high-level, and I can't find >any examples of implementing extract. In S3, I can use [.Date as my >example, but I can't find the equivalent for S4.See the source code for an S4 "[" method. I was unable to convert all S3 methods to S4, so you will see that some S3 methods remain (e.g., as.data.frame.mondate); S3methods=TRUE in the class definition as a result. I wrote this package to solve essentially your problem. If it falls short for you somehow, please me know. Thanks, - Dan Murphy [[alternative HTML version deleted]]