Assignment #7

For this assignment, I used the built-in mtcars dataset in R. I loaded it using data("mtcars") and checked the structure with str(mtcars). The class shows it is a data.frame, and typeof(mtcars) shows its base type is actually a list. When I ran isS4(mtcars), it returned FALSE, meaning it is not an S4 object. So mtcars is an S3 object.

A generic function is a function that works differently depending on the object’s class. Examples are summary(), print(), and plot(). When I run summary(mtcars), R automatically uses the method made for data frames. That is method dispatch. To create an S3 example, I made a list with name, age, and GPA, then assigned it a class using class(student_s3) <- "student". I also created a custom print method. This shows how simple and flexible S3 is. For S4, I used setClass() to formally define a class with slots and their data types. Then I created an object using new(). S4 is stricter because you must define everything first.

To tell which OO system an object uses, I check class() and isS4(). To find the base type, I use typeof(). The main difference is that S3 is informal and flexible, while S4 is more structured and strict. S3 is easier to use, but S4 is better for more complex systems.

macauleywilson/r-programming-assignments






Comments

Popular posts from this blog

Assignment #5

Assignment #4

Assignment 10