[R] Definition of generic function for subclasses

Martin Morgan mtmorgan at fhcrc.org
Tue Mar 13 14:36:48 CET 2012

On 03/13/2012 04:34 AM, Alexander wrote:
> Hi,
> I am working on a project, which contains S4 classes and subclasses. Lets
> assume the following organisation:
> A: S4 Class
> B,C: inherit from A
> D,E,F,G: inherit from B
> H,I: inherit from C
> I want to define now a generic function, which returns me the name of the
> class. I can now write the function with "A" in the signature. Is there any

?class for this function

> reason to write the function for B,C, D,E,... with "B","C","D","E", .. in
> the signature ? I can imagine that it can become a mess if for example I

Implement the method at the lowest (highest?) level in the hierarchy as 
possible -- so on "A" only for the example of class.

> write a function for "A" and a special function for "I" (lets assume, I is
> the only exception).

If 'I' is somehow special then write a method for it alone

   setClass("A"); setClass("C", "A"); setClass("I", "C")

   setGeneric("cls", function(x, ...) standardGeneric("cls"))
   setMethod(cls, "A", function(x, ...) as.vector(class(x)))
   setMethod(cls, "I", function(x, ...) tolower(as.vector(class(x))))

and then

 > cls(new("C"))
[1] "C"
 > cls(new("I"))
[1] "i"

> Have you any best-work-pratice to share ?

Keep your class hierarchy simple and relevant to your actual problem.


> Thanks
> Alexander
> --
> View this message in context: http://r.789695.n4.nabble.com/Definition-of-generic-function-for-subclasses-tp4468837p4468837.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> 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.

Computational Biology
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109

Location: M1-B861
Telephone: 206 667-2793

More information about the R-help mailing list