[Rd] inconsistencies between ?class and ?UseMethod

cberry at tajo.ucsd.edu cberry at tajo.ucsd.edu
Wed Dec 5 06:40:07 CET 2012


Hervé Pagès <hpages at fhcrc.org> writes:

> Hi,
>
> The 2 man pages give inconsistent description of class():
>
> Found in ?class:
>
>      If the object does not have a class attribute, it has an implicit
>      class, ‘"matrix"’, ‘"array"’ or the result of ‘mode(x)’ (except
>      that integer vectors have implicit class ‘"integer"’).
>
> Found in ?UseMethod:
>
>      Matrices and arrays have class ‘"matrix"’ or‘"array"’ followed
>      by the class of the underlying vector.
>      Most vectors have class the result of ‘mode(x)’, except that
>      integer vectors have class ‘c("integer", "numeric")’ and real
>      vectors have class ‘c("double", "numeric")’.
>
> So according to ?UseMethod, class(matrix(1:4)) should be
> c("matrix", "integer", "numeric"), which is of course not the case:
>
>   > class(matrix(1:4))
>   [1] "matrix"
>
> I wonder if this was ever true, and, if so, when and why it has changed.


It still is in the sense that UseMethod and NextMethod dispatch in that
manner on implicit classes. It is bit confusing to me that class()
doesn't report all the implicit classes (like the first error message
below) and inherits() only admits what class() has told.

Note what the first error message below says and how the succesive calls
for afun() work as methods are added to the generic.

If you set a class attribute then the picture changes. I do not see where
this is documented, but it looks like once a class attribute is set, the
implicit classes go away - per the last error message.

> afun <- function(x) UseMethod("afun",x)
> afun(matrix(1L,nc=1))
Error in UseMethod("afun", x) : 
  no applicable method for 'afun' applied to an object of class
  "c('matrix', 'integer', 'numeric')"
> afun.numeric <- function(x) cat("numeric",x,"\n")
> afun(matrix(1L,nc=1))
numeric 1 
> afun.integer <- function(x) cat("integer",x,"\n")
> afun(matrix(1L,nc=1))
integer 1 
> afun.matrix <- function(x) cat("matrix",x,"\n")
> afun(matrix(1L,nc=1))
matrix 1 
> afun.matrix <- function(x) NextMethod()
> afun(matrix(1L,nc=1))
integer 1 
> afun.fooey <- function(x) NextMethod()
> my.mat <- matrix(1L,nc=1)
> afun(my.mat)
matrix 1 
> class(my.mat) <- "fooey"
> afun(my.mat)
Error in NextMethod() : no method to invoke
> 

> Anyway, an update to ?UseMethod would be welcome. 

I wonder if "except with implicit" would improve over "with some
interpolated" in ?class here:

"...in R UseMethod dispatches on the class as returned by class (with
some interpolated classes: see the link)"

HTH,

Chuck

> Or, documenting
> class() in only 1 place seems even better (more DRY principle).
>
> Thanks,
> H.

-- 
Charles C. Berry                            Dept of Family/Preventive Medicine
cberry at ucsd edu			    UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, CA 92093-0901



More information about the R-devel mailing list