[R] Derived classes
ggrothendieck at gmail.com
Fri Sep 5 07:33:35 CEST 2008
# constructor for Square
makeSquare <- function(name, side) structure(list(name = name, side =
side), class = c("Square", "Shape"))
getName <- function(shape) UseMethod("getName")
# Shape method
getName.Shape <- function(shape) shape$name
getArea <- function(shape) UseMethod("getArea")
# Square method
getArea.Square <- function(shape) shape$side ^ 2
sq <- makeSquare("a", 10)
getName(sq) # inherits getName method from Shape class
getArea(sq) # uses getArea method for Square class
On Thu, Sep 4, 2008 at 11:56 PM, <rkevinburton at charter.net> wrote:
> Coming from a C++ and C# background I would like to know how inheritance works with 'R'. The classical example is I can define an abstract class 'Shape' and have an array of 'Shape's but each instance could be a Circle, Square, Triangle, etc. because they all derive from 'Shape'. At runtime if I wish I can tell the type of the 'Shape' using various language specific operators. In 'R' it seems that each 'function' in general returns an object that is specific to that function. For example 'stl' returns an 'stl' object, 'lm' retuirns an 'lm' object, 'kmeans' returns a 'kmens' object etc. If I have an array of these objects what can I use to tell the type of object in 'R' and runtime? Any examples would be helpful.
> Thank you.
> R-help at r-project.org mailing list
> 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