Objects in R

Motivation and relevance

S3

Example stats::lm()

Objects

Generic and methods

Discovery

Exercise: a minimal class. Implement a minimal class MyClass and a print method that provides a tidy summary of the object. Hints: structure() with argument class, list(), class(), cat to print.

Exercise: a simple data base. Implement a minimal class containing people and their occupations. Implement functions and methods to create and print the class, and to subset the class.

S4

Exercise a minimal class. Use setClass to implement a simple class that represents people and their occupation. Use setMethod to write a show method to display the class in a reasonable way, including when the class has a very large number of elements.

.Empl <- setClass("Empl",
    representation(person="character", job="character"))

setMethod(show, "Empl", function(object) {
    len <- length(object@person)
    cat("class: ", class(object), " (n =", len, ")\n", sep="")
    cat("person:", head(object@person), if (len > 6) "...", "\n")
    cat("job:", head(object@job), if (len > 6) "...", "\n")
})
## [1] "show"
## attr(,"package")
## [1] "methods"

.Empl()
## class: Empl (n =0)
## person:  
## job:
.Empl(person=c("Xavier", "Melanie", "Octavio"),
      job=c("Leader", "Innovator", "Doer"))
## class: Empl (n =3)
## person: Xavier Melanie Octavio 
## job: Leader Innovator Doer
.Empl(person=LETTERS, job=letters)
## class: Empl (n =26)
## person: A B C D E F ... 
## job: a b c d e f ...

Reference classes

Example: ShortRead::FastqStreamer()

library(ShortRead)
example(FastqStreamer)

Why a reference class?

Some design decisions:

And…