[Rd] surprisingly, S4 classes with a "dim" or "dimnames" slot are final (in the Java sense)

Hervé Pagès hpages at fredhutch.org
Tue Jun 6 03:08:24 CEST 2017


It's nice to be able to define S4 classes with slots that correspond
to standard attributes:

   setClass("A1", slots=c(names="character"))
   setClass("A2", slots=c(dim="integer"))
   setClass("A3", slots=c(dimnames="list"))

By doing this, one gets a few methods for free:

   a1 <- new("A1", names=letters[1:3])
   names(a1)     # "a" "b" "c"
   a2 <- new("A2", dim=4:3)
   nrow(a2)      # 4
   a3 <- new("A3", dimnames=list(NULL, letters[1:3]))
   colnames(a3)  # "a" "b" "c"

However, when it comes to subclassing, some of these slots cause
problems. I can extend A1:

   setClass("B1", contains="A1")

but trying to extend A2 or A3 produces an error (with a non-informative
message in the 1st case and a somewhat obscure one in the 2nd):

   setClass("B2", contains="A2")
   # Error in attr(prototype, slotName) <- attr(pri, slotName) :
   #   invalid first argument

   setClass("B3", contains="A3")
   # Error in attr(prototype, slotName) <- attr(pri, slotName) :
   #   'dimnames' applied to non-array

So it seems that the presence of a "dim" or "dimnames" slot prevents a
class from being extended. Is this expected? I couldn't find anything
in TFM about this. Sorry if I missed it.


Hervé Pagès

Program in Computational Biology
Division of Public Health Sciences
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N, M1-B514
P.O. Box 19024
Seattle, WA 98109-1024

E-mail: hpages at fredhutch.org
Phone:  (206) 667-5791
Fax:    (206) 667-1319

More information about the R-devel mailing list