[R] A question on validity checking for S4 classes

From: Berton Gunter <gunter.berton_at_gene.com>
Date: Thu 04 Aug 2005 - 09:18:48 EST


(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@.Data<=0))'Must be positive numbers' + else TRUE)


Name: .Data
Class: numeric

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.

"The business of the statistician is to catalyze the scientific learning process." - George E. P. Box

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Thu Aug 04 09:23:29 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 15:03:37 EST