[R] R.oo and S4?

Henrik Bengtsson hb at stat.berkeley.edu
Mon Oct 26 20:10:33 CET 2009


There are two basic class method dispatching mechanisms in R: S3 and
S4.  These are not R.oo.

>From a *design* point of view, S3 and S4 are rather similar, or more
precisely, you can do the same things in both if you're careful.  From
an implementation point of view, they are different, and the code you
write will look different.  S4 provides more features out of the box
and is more "robust" in the sense that it tries to protect you from
your own mistakes.  It also provides methods to inspect S4 objects and
so on.

The R.methodsS3 package provides setMethodS3() [and implicitly
setGenericS3()] for conveniently generating S3 methods.  Using
setMethodS3() is the closest you can get to setMethod() for S4 still
staying in the S3 world.

The R.oo package utilizes R.methodsS3 for defining a generic "root"
class Object, which is therefore by definition based on S3.  You can
extend Object without your own custom-made classes.  The main thing
with the Object class is that it provides a reference variables, that
is, you can change the value of a field of an object without creating
a new copy.  Example:

foo <- function(obj, ...) {
  obj$bar <- 2;
}

obj <- Object();
obj$bar <- 3;
foo(obj);
print(obj$bar)  # Is now equal to 2.

Note that you did not have to do:

obj <- foo(obj);

That is the simple story.

Technically there is nothing preventing having a similar Object class
based on the S4 system, but it has just not been implemented.  Thus,
comparing R.oo/Object and S4 does not really make sense.

I use R.methodsS3/R.oo/Object for almost all of my work.  It has been
especially useful for the development of the aroma.affymetrix package,
which now, if including related packages contains 85,000 lines of
source code.  The use of reference variables becomes natural to
developers when you interact with external resources such as file
systems, data bases etc.  At a lower level, it make more sense to
treat everything as functions where the calling a function has/should
not have any side effects.

There is *a lot* to understand about the above, if you decide to dig
into the details.

/Henrik
R.oo author.

On Mon, Oct 26, 2009 at 11:47 AM, Peng Yu <pengyu.ut at gmail.com> wrote:
> There are different way to make R classes. I know R.oo and S4. I'm
> wondering which one is the current popular one. Which one is current
> recommended when make new R packages? Thank you!
>
> ______________________________________________
> 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