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

Peng Yu pengyu.ut at gmail.com
Tue Oct 27 04:41:17 CET 2009


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

setGeneric('setx<-', function(.object,value){
      standardGeneric('setx<-')
    }
    )

setReplaceMethod(f='setx', signature='A',
    def=function(.object,value){
      .object at x<-value
      return(.object)
    }
    )

a=new(Class='A',x=10)
print(getx(a))

setx(a)<-5
print(getx(a))




More information about the R-help mailing list