[R] Defining class as a member of another class

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sun Jun 28 10:56:36 CEST 2009


Wacek Kusnierczyk wrote:
> Martin Morgan wrote:
>> Gabor Grothendieck wrote:
>>  
>>> Try this:
>>>
>>>    
>>>> setClass("zoo")
>>>>       
>>> [1] "zoo"
>>>     
>>
>> 'zoo' is I guess intended as an S3 class (from library zoo), so
>> setOldClass('zoo') is appropriate. Otherwise, setClass("zoo") creates a
>> new virtual class.
>>
>>  
>>>> setClass("Work",representation=(x="zoo"))
>>>>       
>>
>> This syntax representation=(x="zoo") is doing something quite strange;
>>   
> 
> Strange?  If there's is something strange here, it's is the idea that
> 
>    setClass('bar', representation=c('foo'))
> 
> creates a subclass of 'foo', while
> 
>    setClass('bar', representation=c(x='foo'))
> 
> creates a class with 'foo' as a component.  it's just a design choice, 
> but it's confusing and surely begging for trouble.  but given this is as 
> it is, there is nothing strange with
> 
>    setClass('bar', representation=(x='foo'))
> 
> as far as i am able to understand r, it's equivalent to
> 
>    x = 'foo'
>    setClass('bar', representation='foo')
> 
> hence, bar extends foo.  just a little and useless pattern.

Yes, assuming standard evaluation. I think the point was that if you 
were expecting it to generate a slot "x", then setClass() would need to 
do something strange internally -- recognizing the assignment and 
deparsing its LHS for the component name.

Having results depending on whether or not a character vector is named 
does look like an accident waiting to happen, I agree. However, as of 
2.9.0, Martin's code doesn't seem to actually work:

 > setClass("Work",representation=c(x="integer"))
Error in validObject(.Object) :
   invalid class "classRepresentation" object: invalid object for slot 
"slots" in class "classRepresentation": got class "character", should be 
or extend class "list"

The documentation says that representation is a named _list_, so you'd 
want representation=list(x="integer") to get slot "x".

The actual implementation does have

         if (is.character(representation) && length(representation) ==
             1L && is.null(names(representation)))
             representation <- list(representation)

which is what allows representation="integer" to work. IIUC, this is a 
compatibility feature for a compatibility feature.


-- 
    O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
   c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
  (*) \(*) -- University of Copenhagen   Denmark      Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)              FAX: (+45) 35327907




More information about the R-help mailing list