Module # 7 R Object: S3 vs. S4 assignment
data("mtcars")
head(mtcars, 6)
str(mtcars)
class(mtcars)
typeof(mtcars)
What I found:
-
class(mtcars)→"data.frame" -
typeof(mtcars)→"list"(because data frames are lists under the hood) -
str(mtcars)shows it’s a list of columns, each column is numeric. Yes. Generic functions work great with
mtcars.A generic function is a function that chooses which version of the function to run based on the class of the object you pass in.
Example:
print()is a generic.print(mtcars) # uses print.data.frame behind the scenes
summary(mtcars) # uses summary.data.frameTo prove it’s generic:
isS4(mtcars) # FALSE
methods("print") # shows lots of print methods
methods("summary")If a generic function didn’t work, it would usually be because the object’s class has no method implemented for that generic (so it falls back to a default method or errors).
Step 3 — Can S3 and S4 be assigned to this dataset?
✅ S3 can be assigned easily by setting a class attribute.
✅ S4 can be assigned by defining an S4 class and usingnew().1) How do you tell what OO system (S3 vs. S4) an object is associated with?
Use these:
class(mtcars) # shows S3 class name(s)
isS4(mtcars) # tells if it’s an S4 object-
If
isS4(x)is TRUE → it’s S4 -
If it has a
class()butisS4()is FALSE → it’s almost always S3
Also helpful:
methods(class = "data.frame")2) How do you determine the base type (like integer or list) of an object?
Use:
typeof(mtcars)
mode(mtcars)
storage.mode(mtcars)For data frames:
-
typeof(mtcars)is"list"because each column is stored as an element of a list.
3) What is a generic function?
A generic function is a function that dispatches (chooses) a method based on an object’s class.
Examples:
-
print(x)callsprint.classname(x)if it exists -
summary(x)callssummary.classname(x)if it exists
To check if something is generic:
is.primitive(summary) # not always helpful
methods("summary")4) What are the main differences between S3 and S4?
S3
-
Informal, simple
-
Classes are just a
classattribute -
Methods named like
generic.class -
No strict definition of fields/structure
-
Fast to create and flexible
S4
-
Formal and strict
-
You define a class with
setClass() -
Objects have slots
-
Stronger checks/validation
-
Methods created with
setGeneric()andsetMethod()
-
Comments
Post a Comment