Module #7 – R Object: S3 vs S4

Download any type of data (from the web or use datasets package) or create your own set.

data(“iris”)
head(iris)

Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
library(“pryr”, lib.loc=”/Library/Frameworks/R.framework/Versions/3.6/Resources/library”)

R Code

Then, on the second step, determine if generic function as discussed in this module can be assigned to your data set, and if not, why?

otype(iris)
[1] “S3”

R Code

S3 – Based on Example in Powerpoint

S4 – Based on Example in Powerpoint

Discussion Questions

How do you tell what OO system (S3 vs. S4) an object is associated with?

You can tell what OO system an object is associated with by how it was created and the methods used. You can also check with the functions otype(___) or isS4(___).

How do you determine the base type (like integer or list) of an object?

You can determine the base type of an object with the class() or typeof() functions.

What is a generic function?

The generic function f() is an operation function which dispatches methods and can be done by f.classname() in S3 and setMethod() in S4

What are the main differences between S3 and S4?

There are many differences between S3 and S4 besides using different functions for their operations such as f.classname() in S3 and then setMethod() in S4. Overall, S3 is single dispatch, more interactive and informal(simpler) while S4 is multi-dispatch, less interactive but more formal(structured) and rigorous.

My GitHub Repository- https://github.com/mslement/IntroRProgrammingSlement/blob/master/S3%20and%20S4

Leave a comment

Design a site like this with WordPress.com
Get started