[R] Object-oriented programming in R
Luc Villandre
villandl at dms.umontreal.ca
Wed May 27 18:00:27 CEST 2009
Dear R-users,
I have very recently started learning about object-oriented programming
in R. I am far from being an expert in programming, although I do have
an elementary C++ background.
Please take a look at these lines of code.
> some.data = data.frame(V1 = 1:5, V2 = 6:10) ;
> p.plot = ggplot(data=some.data,aes(x=V1, y=V2)) ;
> class(p.plot) ;
> [1] "ggplot"
My understanding is that the object p.plot belongs to the "ggplot"
class. However, a new class definition like
> setClass("AClass", representation(mFirst = "numeric", mSecond =
> "ggplot")) ;
yields the warning
> Warning message:
> In .completeClassSlots(ClassDef, where) :
> undefined slot classes in definition of "AClass": mSecond(class
> "ggplot")
The ggplot object is also a list :
> is.list(p.plot)
> [1] TRUE
So, I guess I could identify mSecond as being a list.
However, I don't understand why "ggplot" is not considered a valid slot
type. I thought setClass() was analogous to the class declaration in
C++, but I guess I might be wrong. Would anyone care to provide
additional explanations about this?
I decided to explore object-oriented programming in R so that I could
organize the output from my analysis in a more rigorous fashion and then
define custom methods that would yield relevant output. However, I'm
starting to wonder if this aspect is not better suited for package
builders. R lists are already very powerful and convenient templates.
Although it wouldn't be as elegant, I could define functions that would
take lists outputted by the different steps of my analysis and do what I
want with them. I'm wondering what the merits of both approaches in the
context of R would be. If anyone has any thoughts about this, I'd be
most glad to read them.
Cheers,
--
*Luc Villandré*
/Biostatistician
McGill University Health Center -
Montreal Children's Hospital Research Institute/
More information about the R-help
mailing list