Assignment #7 - Exploring R's Object Oriented System (S3 & S4)

 R code and outputs: 




Questions:

How can you tell whether an object uses S3 or S4? (Which functions inspect its class system?)

To determine if an object uses S3 or S4, the first check can be done with the isS4( ) function. If it returns TRUE, then it is an S4 object; otherwise, it is likely an S3. Another check can be performed with the class(x) function to determine the labeling format. S3 classes are typically simple, lists, and data frames. S4 classes generally are more complex, with slots and data types. 

How do you determine an object's underlying type (e.g., integer vs list)?

To determine an object's underlying type, you can use the function typeof( ). An example output of the object's underlying type would be "list", "double", or "character". To specifically test for an integer or a list, you can use is.integer( ) or is.list( ).

What is a generic function in R?

A generic function in R is one that behaves differently based on the type of object or argument it is given. To determine which type it should run, it uses "method dispatch", inspects it, and proceeds based on the provided input. 

What are the principal differences between S3 and S4 (e.g., method definition, formal class declarations)?

S3 is simple and flexible, only requiring you to create a class by setting the "class" attribute on the object and then defining methods by naming them (e.g., print. myClass). S4 is more structured, requiring you to define the class with setClass( ), including typed slots, and create methods using setMethod( ). S3 only dispatches on the first argument, whereas S4 supports multiple.     



Reading:

  • Matloff, N. M. (2011). The Art of R Programming, Chapters 9–10 (pp. 207–231).
  • Wickham, H. (2015). R Packages: Organize, Test, Document, and Share Your Code, Chapters 2–3 (pp. 27–31).

Comments

Popular posts from this blog

Assignment #5: Matrix Algebra in R

Assignment #3: Analyzing 2016 data “Poll” Data in R

Assignment #4: Visualizing and Interpreting Hospital Patient Data