S3 vs. S4
Using the built-in dataset iris in R, which represents the measurements of iris flowers, I tried a few generic functions to see if they could be assigned to the data set.
data("iris")
class(iris)
print(iris)
summary(iris)
head(iris, 3)
The generic functions print, summary, and head all work on the dataset iris because it has the data.frame class. Methods already exist for this class, so the function is called automatically.
Since class(iris) returns "data.frame" but isS4(iris) returns FALSE, I know that iris is already an S3 object. S4 can be assigned to the dataset by creating an S4 class and converting it.
isS4( ) will test if an object is S4, resulting in TRUE or FALSE. If FALSE, then do is.object( ), and if that is TRUE, the object is S3.
2. How do you determine the base type (like integer or list) of an object?
typeof(object) will define the base type of an object.
3. What is a generic function?
A generic function is a function that dispatches methods according to the class of an object. It performs a simple concept like print or plot; it does not do any computations.
4. What are the main differences between S3 and S4?
S3 objects are informal; their classes and methods have been used in R since the beginning. S4 objects are newer to R; they have more formal classes and methods. S4 objects can be rigorous compared to S3 objects, which tend to be simpler yet very interactive. S3 is also only single dispatch, while S4 is multi-dispatch for arguments.
5. In your GitHub, create two examples of S3 and S4.
S3
produce <- list(name = "Apple", amount = 5, price = 3.45)
class(produce) <- "produce"
print.produce <- function(object) {
cat("Name:", object$name, '\n')
cat("Amount:", object$amount, '\n')
cat("Price: $", object$price, '\n')
}
produce
S4
setClass("course", slots = list(name = "character", seats = "numeric", start_time = "numeric"))
course <- new("course", name = "Calculus", seats = 45, start_time = 10)
setMethod("show",
"course",
function(object) {
cat("Course Name:", object@name, '\n')
cat("Seats Available:", object@seats, "\n")
cat("Class Starts:", object@start_time, "A.M.\n")
}
)
course
Comments
Post a Comment