[R] How to reduce key strokes when defining S4 classes?
Peng Yu
pengyu.ut at gmail.com
Tue Oct 27 14:56:26 CET 2009
On Mon, Oct 26, 2009 at 11:56 PM, <mtmorgan at fhcrc.org> wrote:
> Quoting Peng Yu <pengyu.ut at gmail.com>:
>
>> I feel tedious when I define a S4 class and the methods. For each
>> method, I have to call both setMethod and setGeneric (or both
>> setReplaceMethod and setGeneric). I would like a more compact grammar
>> so that I can reduce the key strokes. I'm wondering if there is a
>> better way available.
>>
>> setClass(
>> Class='A',
>> representation=representation(
>> x='numeric'
>> )
>> )
>>
>> setMethod(
>> f='initialize',
>> signature='A',
>> definition=function(.Object,x){
>> cat("~~~ A: initializator ~~~\n")
>> .Object<-callNextMethod(.Object,x=x)
>> return(.Object)
>> }
>> )
>>
>> setGeneric('getx', function(object){
>> standardGeneric('getx')
>> }
>> )
>>
>> setMethod('getx', 'A',
>> function(object){
>> return(object at x)
>> }
>> )
>
> in some sense getx is redundant; x(obj) can only extract a value; more so
> with setx(obj) <- value and x(obj) <- value (illustrating partly that 'x' is
> a poor name for a slot).
>
>>
>> setGeneric('setx<-', function(.object,value){
>> standardGeneric('setx<-')
>> }
>> )
>>
>> setReplaceMethod(f='setx', signature='A',
>> def=function(.object,value){
>> .object at x<-value
>> return(.object)
>> }
>> )
>
> one can create ad hoc getter / setter writers (e.g., in the Bioconductor
> GSEABase package), but in the long run I have found these to require more
> thought than the saved keystrokes are worth. You might be more clever /
> disciplined than I. It's tempting to write getters / setters as simple
> functions (setGeneric / setMethod is required because the defined 'generic'
> isn't really that generic, it's just an idiosyncratic accessor) but in the
> long run this also doesn't seem to work well.
I just gave some examples on getters and setters. But I didn't only
mean getters and setters. Other methods also need the associated two
functions (setGeneric and setMethod) for their definition. I'd wish
there is a more cleaner way to define a method. One drawback of the
current way is the redundancy in the code. For example, 'getx' appears
twice (in both setGeneric and setMethod). This redundancy causes a
higher maintenance cost than if there were no such redundancy.
>> a=new(Class='A',x=10)
>> print(getx(a))
>>
>> setx(a)<-5
>> print(getx(a))
>>
>> ______________________________________________
>> R-help at r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
>
>
>
More information about the R-help
mailing list