Object orientation in R: S3, S4 and Reference Class

11

The R has, among others, three main forms of object orientation:

  • S3;
  • S4; e,
  • Reference Classes.

What are the main differences between the three methods?

And how to implement them (preferably provide a minimal and simple example with code implementing each one)?

    
asked by anonymous 12.09.2014 / 15:34

2 answers

8

The idea of S3 and S4 in R is to use generic functions (which serve for different objects as a parameter), but nevertheless ensure that this function will behave according to the type (= class) of the object that you is sending as a parameter.

For example, if you call the summary function and pass as a linear function parameter using lm , it will return the coefficients etc. If you call this function with a data.frame, it will return a summary of the columns. For different inputs, this function (s) has different methods.

In the S3 paradigm, you create the generic function like (ex: summary ) - see code below too

summary<- function (arg1, arg2,…)
    UseMethod("summary")

In general, the UseMethod function will get the first argument that you sent to the generic function ( summary , in that case), look at what is defined as your class, and dispatch accordingly. The UseMethod() function does this, searches for a function named summary.nomeDaSuaClasse , and executes it with the parameters you have sent.

Advantages: I think it's already obvious Disadvantages: you have no absurdity control. You can create any object and call any class (see example code). You have to trust the programmer. Second disadvantage, S3 only looks at the class of a parameter to make the dispatch. I think there are more disadvantages, but I remember those two now.

The S4 class solves these problems. But I'll stop here. And a little more complicated and I think the answer would be very long. I'll summarize it as follows: you use a function ( setGeneric() ) to create your generic function. Then you use setMethod() to create the corresponding methods, and then several other functions to define how this generic function and its methods will operate.

If it is safe and your application is relatively simple, I see no problem in using S3.

I hope you have helped.

# criando um objeto (vetor com uma string)
meuObjeto <- "string"

# Veja a estrutura do seu objeto:
str(meuObjeto)

#Agora adicione mais strutura: uma classe
class(meuObjeto) <- 'minhaClasse'

# Veja a estrutura do seu objeto:
str(meuObjeto)

# Exemplos de objetos S3 (summary)
exClass_glm       <- glm(c(20:1) ~ c(1:20) )
exClass_dataframe <- data.frame(1:20)
str(exClass_glm) # a lot of structure
class(exClass_glm) # ... and two classes

# veja a diferenca: nao ha methodo para a clsse "minhaClasse", porque nao definimos nada
summary(exClass_glm)
summary(exClass_dataframe)
summary(meuObjeto)

# mas se voce define um metodo para sua classe....
summary.minhaClasse <- function (x,y,...) {
print('Hey, olha so !!')
paste('minha string e:',meuObjeto)
}
summary(meuObjeto)

# mas S3 e coracao de mae e aceita qualquer coisa, o que pode gerar erro em algum momento do codigo
x <- 3
summary(x)
class(x) <- 'glm'
summary(x)
    
19.09.2014 / 05:14
6

I suggest reading some very clear texts on the question that was posed:

Documents

CRAN project manuals

Similar issues in SE and SO

15.09.2014 / 20:12