[Rd] Failure to preserve package attribute when coercing S4 objects (PR#6904)

Jonathan.Swinton at astrazeneca.com Jonathan.Swinton at astrazeneca.com
Fri May 21 16:09:18 CEST 2004


If a class is derived from a superclass using 'contains', then coercion of
an object from the class to the superclass fails to preserve the 'package'
attribute of class of the object.
This occurs only when the derived class has no additional slots.
This is a problem because the 'new' function relies on the exact identity
of the class, including the package attribute.  

This can clearly be worked around by the introduction of dummy slots, but it
took me some time to track down.

> setClass("baseClass",representation(a="numeric"))
[1] "baseClass"
> setClass("fancyClass",contains="baseClass")
[1] "fancyClass"
>
setClass("fancyClassExtraSlots",representation(b="numeric"),contains="baseCl
ass")
[1] "fancyClassExtraSlots"
> 
> 
> aFP <- new("fancyClass",a=2)
> aFP2 <- new("fancyClassExtraSlots",a=2,b=3)
> 
> aBP <- new("baseClass",a=1)
> aBPcast <- as(aFP,"baseClass")
> aBPcast2 <- as(aFP2,"baseClass")
> # all the baseClass objects have the right class
> sapply(list(aBP,aBPcast,aBPcast2),class)
[1] "baseClass" "baseClass" "baseClass"
> # however the object cast from a fancy class with no slots has a different
package attribute
> sapply(list(aBP,aBPcast,aBPcast2),function(x)attr(class(x),"package"))
[[1]]
[1] ".GlobalEnv"

[[2]]
NULL

[[3]]
[1] ".GlobalEnv"

> new("baseClass",aBP) # works
An object of class "baseClass"
Slot "a":
[1] 1

> new("baseClass",aBPcast) # fails. Note the error message!
Error in initialize(value, ...) : Initialize method returned an object of
class "baseClass" instead of the required class "baseClass"

> new("baseClass",aBPcast2) # works
An object of class "baseClass"
Slot "a":
[1] 2


platform i386-pc-mingw32
arch     i386           
os       mingw32        
system   i386, mingw32  
status                  
major    1              
minor    9.0            
year     2004           
month    04             
day      12             
language R

Jonathan Swinton, Statistical Scientist, Computational Biology, Pathway
Analysis, Global Sciences and Information,  x29400, 19F44 Mereside Alderley
Park.



More information about the R-devel mailing list