S3 System Exercises

This notebook contains exercises to help you practice working with the S3 system in R. Complete the exercises below to improve your understanding of S3 classes, methods, and generic functions.

Exercise 1: Creating an S3 Class

Create an S3 class called student with the following attributes: - name (character) - age (numeric) - grades (numeric vector)

Then, create an instance of this class for a student named “Alice” who is 20 years old and has grades 85, 92, and 78.

# Your code here

Exercise 2: Creating a Method

Create a method for the generic function print that works with your student class. The method should display the student’s name, age, and average grade.

# Your code here

Exercise 3: Creating a Generic Function

Create a generic function called get_letter_grade that takes a numeric grade as input and returns the corresponding letter grade according to the following scale: - 90-100: A - 80-89: B - 70-79: C - 60-69: D - Below 60: F

Then, create a method for this generic function that works with your student class. The method should return a vector of letter grades corresponding to the student’s numeric grades.

# Your code here

Exercise 4: Inheritance

Create a new S3 class called graduate_student that inherits from the student class. Add an additional attribute called research_topic (character).

Create an instance of the graduate_student class for a student named “Bob” who is 25 years old, has grades 88, 94, and 91, and is researching “Machine Learning”.

# Your code here

Exercise 5: Method Dispatch

Create a method for the print generic function that works with your graduate_student class. This method should display all the information from the student class print method, as well as the research topic.

# Your code here

Now, test your classes and methods by creating instances of both student and graduate_student classes and calling the print and get_letter_grade functions on them.

# Your code here

Great job completing these exercises! Check your answers in the accompanying answer key.

LS0tCnRpdGxlOiAiUzMgU3lzdGVtIEV4ZXJjaXNlcyBpbiBSIgphdXRob3I6ICJOYXllbCBCZXR0YWNoZSIKZGF0ZTogImByIFN5cy5EYXRlKClgIgpvdXRwdXQ6IGh0bWxfbm90ZWJvb2sKLS0tCgojIFMzIFN5c3RlbSBFeGVyY2lzZXMKClRoaXMgbm90ZWJvb2sgY29udGFpbnMgZXhlcmNpc2VzIHRvIGhlbHAgeW91IHByYWN0aWNlIHdvcmtpbmcgd2l0aCB0aGUgUzMgc3lzdGVtIGluIFIuIENvbXBsZXRlIHRoZSBleGVyY2lzZXMgYmVsb3cgdG8gaW1wcm92ZSB5b3VyIHVuZGVyc3RhbmRpbmcgb2YgUzMgY2xhc3NlcywgbWV0aG9kcywgY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