Skip to content
Prev 40260 / 63424 Next

By default, `names<-` alters S4 objects

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.