Week 7: S3 vs S4 objects

Hi everyone!

This week we learned about S3 and S4 objects. Objects in R store data elements and are part of classes where you can use different methods or functions to operate on them. An object can be a vector, variable, list, matrix, etc. In R, the two types of objects are S3 used for informal methods from the beginning and S4 used for formal methods in classes and methods developed later. 


Download any type of data (from the web or use datasets package) or create your own set. 

Then, on the second step, determine if generic function as discussed in this module can be assigned to your data set, and if not, why? (Example, here is list of data set in R)
data("mtcars")
head (mtcars, 6)
list(mtcars, 6)

In third and last step, explore if S3 and S4 can be assigned to your data set.

I created a dataset of two potential employees with their name, age, years of experience, and the role they are applying to. The generic function print works, but functions such as mean do not because the data is in lists. This dataset can be used with both S3 and S4 functions. I combine the print functions steps and the hiring message as a function into one method. In S3, two classes had to be made and the method had to be called twice as a function with the object in ( ), but in S4 setting the class and method allowed us to receive the results just by calling the object's name.

Check this out in GitHub!


In your blog, discuss the following questions:

1. How do you tell what OO system (S3 vs. S4) an object is associated with?

You can tell which OO system was used to create an object using the otype() function from the pryr library. 

2. How do you determine the base type (like integer or list) of an object?

The mode() function can help you determine the base type of an object. For example, mode("dog") would be character.

3. What is a generic function?

A generic function is a function that is called using a generic dispatcher such as print() and can be applied to different types of inputs for different results based on an uniform interface.

4. What are the main differences between S3 and S4?

S3 is the most commonly used and allows you to easily change the class of existing objects. A simple list assigned to a class would be a S3 object. The steps to create this object would be to define the class through a constructor code, build the list, reference the variables in the function, and utilize the method.

S4 has different steps to create an object starting with the SetClass(), new() to create the object, @ to reference variables, setMethod() to set the methods used. S4 does not let you change the class of existing objects which is good for safety of data.

-Ramya's POV


Comments

Popular posts from this blog

Week 6: Doing Math P2