[Rd] By default, `names<-` alters S4 objects

Hervé Pagès hpages at fhcrc.org
Sun May 15 00:47:18 CEST 2011


Hi,

I was stumped by this. The two S4 objects below looked exactly the same:

   > a1
   An object of class "A"
   Slot "aa":
   integer(0)
   > a2
   An object of class "A"
   Slot "aa":
   integer(0)

   > str(a1)
   Formal class 'A' [package ".GlobalEnv"] with 1 slots
     ..@ aa: int(0)
   > str(a2)
   Formal class 'A' [package ".GlobalEnv"] with 1 slots
     ..@ aa: int(0)

But they were not identical:

   > identical(a1,a2)
   [1] FALSE

Then I found that one had a "names" attribute but not the other:

   > names(attributes(a1))
   [1] "aa"    "class" "names"
   > names(attributes(a2))
   [1] "aa"    "class"

   > names(a1)
   NULL
   > names(a2)
   NULL

Which explained why they were not reported as identical.

After tracking the history of 'a1', I found that it was created with
something like:

   > setClass("A", representation(aa="integer"))
   [1] "A"
   > a1 <- new("A")
   > names(a1) <- "K"
   > names(a1)
   NULL

So it seems that, by default (i.e. in the absence of a specialized
method), the `names<-` primitive is adding a "names" attribute to the
object. Could this behaviour be modified so it doesn't alter the object?

Thanks,
H.


-- 
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 fhcrc.org
Phone:  (206) 667-5791
Fax:    (206) 667-1319



More information about the R-devel mailing list