[Rd] Extract/format/show for S4 objects

Gabor Grothendieck ggrothendieck at gmail.com
Tue Jun 8 16:30:47 CEST 2010


The yearqtr class already rounds off automatically to avoid floating
point effects and handles #1 and #2.

On the other hand if you are just interested in playing around with S4
for its own sake review the source code of the mondate package as an
example of an S4 based date package.

On Tue, Jun 8, 2010 at 10:08 AM, Johann Hibschman <jhibschman at gmail.com> wrote:
> Hi all,
>
> 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.
>
> 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.
>
> Second, is this misguided?
>
> Now for the details.  Given this start:
>
>  library(zoo) # borrowing yearqtr for output.
>  setClass("iqtr", contains="integer")
>  ## Create an iqtr object from a numeric date (e.g. 2000.5).
>  iqtr <- function (x) {
>    iq <- as.integer(floor((as.numeric(x) - 2000) * 4 + 0.0001))
>    new("iqtr", iq)
>  }
>  setMethod("show", "iqtr4",
>            function (object) {
>              cat(format(yearqtr(as.numeric(x) * 0.25 + 2000)))
>            })
>
>
> I have two issues:
>
>  1. Vectors of iqtrs do not display properly.
>     They print, but they don't look like vectors.
>       > iq <- iqtr(seq(2000, 2002, 0.25))
>       > iq
>       2000 Q2 2000 Q2 2000 Q3 2000 Q4 2001 Q2 2002 Q1>
>
>  2. Subsets do not stay in the class.
>       > iq[1:2]
>       > [1] 0 1
>
> Clearly, I'm just not understanding what's going on.  Is there a guide
> for how to make printing, format, subsetting, etc., all work for S4
> classes?
>
> Thanks,
> Johann
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



More information about the R-devel mailing list