[Rd] class of integers

ripley at stats.ox.ac.uk ripley at stats.ox.ac.uk
Wed Mar 12 16:23:51 MET 2003


On Wed, 12 Mar 2003, Torsten Hothorn wrote:

> 
> Hi,
> 
> I'm a little bit confused about the class of integers (with yesterdays
> r-devel):
> 
> R> a <- 1:10
> R> class(a)
> [1] "integer"
> R> inherits(a, "integer")
> [1] FALSE
> R> data.class(a)
> [1] "numeric"
> R> is.numeric(a)
> [1] TRUE
> R> inherits(a, "numeric")
> [1] FALSE

inherits needs updating ....

> data.class is consistent with R-1.6.2, ok. The class of "a" is integer,
> also ok. At first: why does "inherits" state that "a" is not of class
> integer nor numeric?


> And at second: one possible way of writing portable code (between 1.6.2
> and 1.7.0) for generics is using:
> 
> foo <- function(y, ...) {
>   if(is.null(class(y)))
>     class(y) <- data.class(y)
>   UseMethod("foo", y, ...)
> }
> 
> foo.default <- function(y, ...) {
>   stop(paste("Do not know how to handle objects of class", class(y)))
> }
> 
> (the thread "[Rd] Methods package is now attached by default" around Jan
> 20th discussed this)
> 
> If I have
> 
> foo.numeric <- function(y, ...)
>   ...
> 
> this works with R-1.6.2 but since foo now dispatches on "class(y)" this
> fails for integers with r-devel. 

Try

foo <- function(y, ...) {
    if(is.null(oldClass(y))) oldClass(y) <- data.class(y)
    UseMethod("foo", y, ...)
}

or for 1.6.2 compatibility

foo <- function(y, ...) {
    if(is.null(attr(y, "class"))) attr(y, "class") <- data.class(y)
    UseMethod("foo", y, ...)
}  

(not actually tested).

> Does this mean that I have to implement
> foo.integer methods?

No, but it is the cleanest route.

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