[Rd] format.data.frame containing S4 class with format method

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon May 17 10:14:49 CEST 2010


On Sun, 16 May 2010, Daniel Murphy wrote:

> Hi again,
>
> I must be misunderstanding something fundamental about how an S4 class
> stored in a data.frame can be persuaded to print according to a desired
> format.

Rather, you are misunderstanding something fundamental about the 
'methods' package.  It is optional, and all unqualified references to 
'generic' and 'method' in other basic packages will be to the original 
S3 concepts (and many predate the 'methods' package).

> The help page says:
>
> format.data.frame formats the data frame column by column, applying the
> appropriate method of format for each column.

So define a 'method', not an 'S4 method'.

You will see that you have defined a function format() in your 
workspace.  That does dispatch S4 methods, but the namespace scoping 
rules protect packages against such masking of base functions.

>
> Here is my class:
>> setClass("A",contains="character")
> [1] "A"
>> a <- new("A", "aaa")
>> a
> An object of class "A"
> [1] "aaa"
>
> I defined my format method to display in uppercase:
>> setMethod("format","A", function(x, ...) toupper(x))
> [1] "format"
>> format(a)
> An object of class "A"
> [1] "AAA"
>
> I looked at the S4 class definition for data.frame (getClass("data.frame"))
> which prompted me to store the instance 'a' into a data.frame as follows:
>> adf<-new("data.frame",list(a), names="a", row.names="1")
>> adf
> Object of class "data.frame"
>    a
> 1 aaa
>
> ... not upper case. The str function clearly shows that the object was
> successfully stored in the data.frame:
>> str(adf)
> 'data.frame':   1 obs. of  1 variable:
> 'data.frame':   1 obs. of  1 variable:
> Formal class 'data.frame' [package "methods"] with 4 slots
>  ..@ .Data    :List of 1
>  .. ..$ :Formal class 'A' [package ".GlobalEnv"] with 1 slots
>  .. .. .. ..@ .Data: chr "aaa"
>  ..@ names    : chr "a"
>  ..@ row.names: chr "1"
>  ..@ .S3Class : chr "data.frame"
>
> Is there another step I should be taking so that "A"'s format method is
> found and used?
>
> Thank you,
>
> Dan Murphy
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-devel mailing list