[R] How to reduce key strokes when defining S4 classes?

mtmorgan at fhcrc.org mtmorgan at fhcrc.org
Tue Oct 27 05:56:36 CET 2009


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.

Martin

>
> 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