Module 7: R Objects S3 vs. S4
For this assignment, I used the built-in dataset mtcars from R (so I didn’t have to download anything). First I loaded it and checked the first few rows to confirm it worked.
Step 1. Data
mtcars is a data frame (32 rows × 11 columns). Since it’s a normal R dataset, it already comes with a class and lots of functions that work with it.
Step 2. Can a generic function be assigned to this dataset? If not, why?
A generic function is a function that chooses which method to run based on the class of the object you pass in (like print(), summary(), or plot()). For mtcars, generic functions already work because mtcars has class "data.frame" (and also behaves like a list under the hood). For example, summary(mtcars) runs the summary.data.frame() method automatically.
If I tried to use a generic function that has no method for a data frame, it wouldn’t know what to do (it would either fall back to a default method or error). That’s basically the “why not” case: the object’s class must have a matching method (or a default method) for the generic.
How do you tell what OO system (S3 vs. S4) an object is associated with?
-
S3: check
class(x)andmethods(class = "classname"). S3 objects usually just have a"class"attribute. -
S4: check
isS4(x)(TRUE/FALSE) andclass(x)will return an S4 class name. S4 objects are created withsetClass()+new()and have formal slots.
How do you determine the base type (like integer or list) of an object?
Use:
-
typeof(x)(internal storage type, like"double","list", etc.) -
mode(x)(older-style; similar but less precise) -
is.integer(x),is.list(x), etc. -
str(x)is also helpful because it shows structure + types.
What is a generic function?
A generic function is a function that dispatches to a class-specific method. Example: calling print(x) will run print.data.frame(x) if x is a data frame, or print.myclass(x) if you wrote your own method for an S3 class named "myclass".
What are the main differences between S3 and S4?
-
S3: informal/simple, class is just an attribute, easy to create, method naming is
generic.class(likeprint.studentS3). Great for quick custom objects. -
S4: formal/strict, you define a class structure with
setClass(), objects have slots, and methods are registered withsetGeneric()/setMethod(). Better when you want strong structure and validation.
Step 3. Explore S3 and S4 with the dataset
mtcars itself is an S3 object (a "data.frame"). For the OO part, I created two simple “student” examples: one in S3 (list + class) and one in S4 (formal class + slots). That shows how each system can be assigned to a dataset-like structure.
https://github.com/zaragz/module7_s3_s4_examples
Comments
Post a Comment