[R] A question on validity checking for S4 classes

Berton Gunter gunter.berton at gene.com
Thu Aug 4 01:18:48 CEST 2005


Folks:

(This is a question on the formal S4 class system). R 2.1.1 on Windows.

I'm pretty sure the following is a failure of my understanding, rather than
a bug, so may I ask for some clarification?

The Green book states that (p. 295) "Objects are checked for validity when
permanently assigned, or explicitly by the function validObject()." The Help
for setValidity() seems silent on the details, however, and this does not
appear to be the R implementation. Here's an example to show why I think
not:

> setClass('posNumber','numeric')
[1] "posNumber"

> setValidity('posNumber',function(object)
+ if(any(object at .Data<=0))'Must be positive numbers'
+ else TRUE)

Slots:
              
Name:    .Data
Class: numeric

Extends: 
Class "numeric", from data part
Class "vector", by class "numeric"

> z<-new('posNumber',1:3)
> z
An object of class "posNumber"
[1] 1 2 3

#### BUT ....
> z<-z-5
> z
An object of class "posNumber"
[1] -4 -3 -2
##### Isn't this where the Green book says validity should be checked?
#####  Further, note that when one does the explicit check:

> validObject(z)
Error in validObject(z) : invalid class "posNumber" object: Must be positive
numbers 

## or when one tries to instantiate 'posNumber' incorrectly:
> z<-new('posNumber',-(1:3))
Error in validObject(.Object) : invalid class "posNumber" object: Must be
positive numbers

So when does R do validity checking? And, in particular, how should I
arrange the classes/validity checking or other methods so that I can assure
that an object of class 'posNumber' consists of positive numbers without
doing an explicit validObject() check? Many thanks and my apologies if I
have misunderstood or overlooked something obvious.

-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
 
"The business of the statistician is to catalyze the scientific learning
process."  - George E. P. Box




More information about the R-help mailing list