Skip to content
Prev 70254 / 398506 Next

Documentation of S3 and S4 classes, inheritance

On 5/23/05, Ross Boylan <ross at biostat.ucsf.edu> wrote:
Here is a working example to try out.  In the call to lik,
the first class in the class vector is "B" so lik.B gets invoked.  
The next method of x is "A" so NextMethod invokes lik.A from 
within lik.B and then returns its result to lik.A which finishes the 
calculation.

lik <- function(x) UseMethod("lik")
lik.A <- function(x) mean(x)
lik.B <- function(x) NextMethod("lik") + sd(x)

x <- structure(1:3, class = c("B", "A"))
lik(x) # 3
See above discussion.
This area seems somewhat controversial with different people stating
different opinions.   IMHO you are probably best off to start with S3 since its
simpler and if you do learn S4 later they are not unrelated so it will make 
it easier than jumping straight into it.  Also you may find you never have to 
go beyond S3 in which case you have saved yourself some time.  I 
personally use S3.

By the way if choosing from S3 and S4 is not enough, there are also 
two CRAN packages that provide additional OO models as well: 
R.oo and proto.