[R] test to see if a s4 property is assigned?

Martin Morgan mtmorgan at fhcrc.org
Fri Sep 17 02:32:56 CEST 2010


On 09/16/2010 02:23 PM, darckeen wrote:
> 
>>
> setClass("person",representation(age="numeric",weight="numeric"),prototype(age=NULL,weight=NULL))
> [1] "person"
>> bob <- new("person",age=30)
> Error in validObject(.Object) : 
>   invalid class "person" object: invalid object for slot "weight" in class
> "person": got class "NULL", should be or extend class "numeric"
> 
> So I guess I can only protoype a property to NULL if its defined as ANY?  I

> is.numeric(NULL)
[1] FALSE

so it makes sense that a slot that is supposed to have numeric values
can't have NULL. You could test for length(bob at weight) == 0 (default
prototype) or is.na(bob at weight) (prototype(weight=NA_numeric_, but maybe
NA and not-defined are different for you) or bob at weight < 0
(prototype(weight=-1L), for instance, or define and use a class that
extends "numeric" and implements a 'defined' method. Might also check
that a defined numeric is exactly length 1.

Martin

> though there might be a way to test if a propery was assigned to get around
> this.  Really kinda turns me off from S4 classes :\



More information about the R-help mailing list