S3 System Exercises - Answer Key

This notebook contains the answers to the exercises on working with the S3 system in R.

Exercise 1: Creating an S3 Class

# Create the student class
student <- function(name, age, grades) {
  structure(list(name = name, age = age, grades = grades), class = "student")
}

# Create an instance of the student class
alice <- student("Alice", 20, c(85, 92, 78))
print(alice)

Exercise 2: Creating a Method

# Create a print method for the student class
print.student <- function(x) {
  cat("Student Name:", x$name, "\n")
  cat("Age:", x$age, "\n")
  cat("Average Grade:", mean(x$grades), "\n")
}

# Test the print method
print(alice)

Exercise 3: Creating a Generic Function

# Create the generic function
get_letter_grade <- function(x) {
  UseMethod("get_letter_grade")
}

# Create a method for numeric input
get_letter_grade.numeric <- function(x) {
  case_when(
    x >= 90 ~ "A",
    x >= 80 ~ "B",
    x >= 70 ~ "C",
    x >= 60 ~ "D",
    TRUE ~ "F"
  )
}

# Create a method for the student class
get_letter_grade.student <- function(x) {
  get_letter_grade(x$grades)
}

# Test the get_letter_grade function
get_letter_grade(alice)

Exercise 4: Inheritance

# Create the graduate_student class
graduate_student <- function(name, age, grades, research_topic) {
  student_obj <- student(name, age, grades)
  structure(c(student_obj, research_topic = research_topic), class = c("graduate_student", "student"))
}

# Create an instance of the graduate_student class
bob <- graduate_student("Bob", 25, c(88, 94, 91), "Machine Learning")
print(bob)

Exercise 5: Method Dispatch

# Create a print method for the graduate_student class
print.graduate_student <- function(x) {
  NextMethod()  # Call the print method of the parent class (student)
  cat("Research Topic:", x$research_topic, "\n")
}

# Test classes and methods
alice <- student("Alice", 20, c(85, 92, 78))
bob <- graduate_student("Bob", 25, c(88, 94, 91), "Machine Learning")

print(alice)
cat("\n")
print(bob)

cat("\nAlice's letter grades:", get_letter_grade(alice), "\n")
cat("Bob's letter grades:", get_letter_grade(bob), "\n")

This completes the exercises and demonstrates the creation and use of S3 classes, methods, and generic functions in R.

LS0tCnRpdGxlOiAiUzMgU3lzdGVtIEV4ZXJjaXNlcyBpbiBSIC0gQW5zd2VyIEtleSIKYXV0aG9yOiAiTmF5ZWwgQmV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