[R] Classes in R

John Fox jfox at mcmaster.ca
Thu Oct 25 22:49:56 CEST 2001


Dear Randall,

At 05:27 PM 10/25/2001 +0100, you wrote:
>Two quick questions.
>
>First, why doesn't using the matrix function actually set the class of the
>resulting object to "matrix"?
>
> > a <- matrix(1,10,10)
> > attributes(a)
>  $dim
>  [1] 10 10
>
>or should I be using?
>
> > a <- matrix(1,10,10); class(a) <- c("matrix");
> > attributes(a)
>$dim
>[1] 10 10
>
>$class
>[1] "matrix"

In R, not all objects have a class attribute, and hence not all objects 
belong to a class. In particular, matrices do not (necessarily) belong to a 
class. A matrix in R is a vector with a length-2 dim attribute.

Perhaps it would be more responsive to ask why you require that the matrix 
a belong to the class 'matrix'?

By the way, there is a Matrix library that creates matrices of class 'Matrix'.

>Second, can somone please send me an example showing how inheritance works
>in R?  The R Language Definition document isn't particularly clear on the
>subject... i.e. NextMethod lacks a good example.

 From R help:

An R ``object'' is a data object which has a class attribute. A class 
attribute is a character vector giving the names of the classes which the 
object ``inherits'' from. When a generic function fun is applied to an 
object with class attribute c("first", "second"), the system searches for a 
function called fun.first and, if it finds it, applied it to the object. If 
no such function is found a function called fun.second is tried. If no 
class name produces a suitable function, the function fun.default is used.

(I realize that this isn't usually what's meant by "object-oriented 
programming" or "inheritance.")

Thus, for example:

 > M <- matrix(1:12, 3, 4)
 > class(M) <- c('a', 'b')
 >
 > print.a <- function (x, ...) {
+     print.matrix(x)
+     NextMethod()
+     }
 >
 > print.b <- function(x, ...) print(as.vector(x))
 >
 > M
      [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
  [1]  1  2  3  4  5  6  7  8  9 10 11 12
 >

I hope that this helps,
  John




-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list