[R] "methods" package changes class types?

ripley@stats.ox.ac.uk ripley at stats.ox.ac.uk
Wed Jan 8 18:24:03 CET 2003


Well, the xtable package is at fault.  One really should not assume an
object has no class, and should only check inheritance.

That function should have

if(is.null(class(x))) class(x) <- data.class(x)
switch(class(x), ....)

On Wed, 8 Jan 2003, Nunoo, Paa K wrote:

> Hi,
>
> Loading the "methods" package into R seems to change the class of a
> character vector from NULL to "character":
>
> > class("abcd")
> NULL
> > library("methods")
> > class("abcd")
> [1] "character"
>
> This can lead to problems. For example the "as.string" function in the
> "xtable" package
> assumes that the class of a character vector is NULL. However this changes
> when the methods
> package is loaded.
>
> Here is a code snippet of the as.string function in the xtable package:
> > library(xtable)
> > as.string
> function (x, file = "", append = FALSE)
> {
>     if (is.null(class(x)))
>         switch(data.class(x), character = return(string(x, file,
>             append)), numeric = return(string(as.character(x),
>             file, append)), stop("Cannot coerse argument to a string"))
>     if (class(x) == "string")
>         return(x)
>     stop("Cannot coerse argument to a string")
                   ^^^^^^
(sic)

> }
>
> Why does the methods package change the class of character vectors?

Because it implements the Green Book (JMC, 1998) where every object has a
class.  It just ensures that: it does not change the class of objects
which already have a class (as far as I know).

> Is there a way around this behavior?

Don't use the methods package?  More seriously, write and use correct
code which handles classing properly.

-- 
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