Module # 7 R Object: S3 vs. S4 assignment
For this assignment, I used the built-in R dataset mtcars, which comes from the R datasets package.
data("mtcars")
head(mtcars, 6)
The mtcars dataset contains information about different car models, including:
- mpg (miles per gallon)
- cyl (number of cylinders)
- hp (horsepower)
- wt (weight)
- am (transmission type)
To check its structure, I got this below:
Output shows:
-
Class:
"data.frame" -
Base type:
"list"
print() and summary() are generic functions.And to check if a function is generic: methods(summary)
This shows different methods like:
- summary.data.frame
- summary.lm
- Since mtcars is a data.frame, R automatically dispatches:
- summary.data.frame(mtcars)
A Generic Function Be Assigned
Because mtcars is an S3 object, data.frame is an S3 class, generic functions like: print() summary() and plot()
automatically dispatch methods for it.
If a dataset does not have a defined class or method, R will use the default method, such as:
summary.default()
If no method exists at all, R can just give an error.
S3 Assignment
Assign a new S3 class to mtcars:
mydata <- mtcars
class(mydata) <- "car_data"
summary.car_data <- function(object) {
cat("Custom Summary for Car Data\n")
cat("Number of Cars:", nrow(object), "\n")
cat("Average MPG:", mean(object$mpg), "\n")
}
Then:
summary(mydata)
This demonstrates S3 method dispatch.
S4 Assignment
setClass("CarData",
slots = list(
data = "data.frame"
))
car_obj <- new("CarData", data = mtcars)
To define a method:
setGeneric("carSummary", function(object) standardGeneric("carSummary"))
setMethod("carSummary", "CarData", function(object) {
cat("S4 Car Summary\n")
cat("Number of Cars:", nrow(object@data), "\n")
})
Then call:
carSummary(car_obj)
Both S3 and S4 can be assigned to this dataset.
1. How do you tell what OO system (S3 vs. S4) an object is associated with?
For S3:
class(object)
S3 objects have a class attribute but no formal slot definition.
For S4:
isS4(object)
If TRUE it is an S4 object.
Also:
slotNames(object)
Only works for S4 objects.
2. How do you determine the base type of an object?
Use:
typeof(object) or mode(object)
For example:
typeof(mtcars)
Returns:
[1] "list"
So even though mtcars is a data.frame, its base type is a list.
3. What is a Generic Function?
A generic function is a function that performs method dispatch based on the object’s class.
Example:
- summary()
- print()
- plot()
It calls class-specific methods like:
- summary.data.frame
- summary.lm
- summary.default
Generic functions can enable polymorphism.
Comments
Post a Comment