[R] Validity check when setting slot
Vitalie S.
vitosmail at rambler.ru
Thu Aug 13 16:43:15 CEST 2009
Hi,
>>
>> RG> Hi,
>> RG> I'm wondering if the following behaviour is normal:
>>
>> RG> setClass('A', representation(number='numeric'), RG>
>> validity=function(object){ RG> if( object at number < -1 )
>> return("Invalid number"); TRUE})
>> >> [1] "A"
>> RG> a <- new('A')
>> RG> a
>> >> An object of class “A”
>> >> Slot "number":
>> >> numeric(0)
>>
>> RG> a at number <- 0
>> RG> a at number <- -3
>> RG> a
>> >> An object of class “A”
>> >> Slot "number":
>> >> [1] -3
>>
Rewriting `@<-` will do the job:
setClass('A', representation(number='numeric'),
validity=function(object){
if( object at number < -1 ) return("Invalid number")
TRUE}
)
setMethod("@<-",
signature(object = "A"),
function (object, name, value){
object <- callNextMethod(object, as.character(substitute(name)),
value)
validObject(object)
return(object)
}
)
> a <- new('A')
> a at number <- 23
> a at number <- -23
Error in validObject(object) : invalid class "A" object: Invalid number
By th way, it seems (to me) that there is a bug in callNextMethod above:
object <- callNextMethod(object, name, value)
or
object <- callNextMethod()
trigger an error:
Error in checkSlotAssignment(object, name, value) :
"name" is not a slot in class "A"
-Vitalie
More information about the R-help
mailing list