[R] why-s of method dispatching

Prof Brian Ripley ripley at stats.ox.ac.uk
Thu Mar 18 09:24:26 CET 2004


On Wed, 17 Mar 2004, Vadim Ogranovich wrote:

> I am having a problem to understand why as.data.frame method doesn't
> dispatch properly on my class:
> 
> > setClass("Foo", "character")
> [1] "Foo"
> > as.data.frame(list(foo=new("Foo", .Data="a")))
> Error in as.data.frame.default(x[[i]], optional = TRUE) : 
>  can't coerce Foo into a data.frame
> 
> I was expecting that this would call as.data.frame.character.

You have set an S4 class and as.data.frame is an S3 generic.

> list(foo=new("Foo", .Data="a"))
$foo
An object of class "Foo"
[1] "a"

and what as.data.frame sees is

> attributes(list(foo=new("Foo", .Data="a"))$foo)
$class
[1] "Foo"
attr(,"package")
[1] ".GlobalEnv"

so thinks this is an S3 class it knows nothing about.

> Another puzzle. If I explicitly call as.data.frame.character() it would
> fail but for a different reason:
> 
> > as.data.frame.character(list(foo=new("Foo", .Data="a")))
> Error in unique.default(x) : unique() applies only to vectors
> 
> I was under an impression that an instance of "Foo" would be welcome
> anywhere a "character" was, but it seems to be more subtle. What am I
> missing?

The difference between S3 and S4 classes.

-- 
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-help mailing list