Chapter 52 S3 Object System
What You’ll Learn:
- S3 classes and objects
- Generic functions and method dispatch
- Inheritance
- Common S3 errors
Key Errors Covered: 15+ S3 errors
Difficulty: ⭐⭐⭐ Advanced
52.2 Creating S3 Objects
💡 Key Insight: Constructor Pattern
# Constructor
new_person <- function(name, age) {
structure(
list(name = name, age = age),
class = "person"
)
}
# Validator
validate_person <- function(x) {
if (!is.character(x$name)) stop("name must be character")
if (!is.numeric(x$age) || x$age < 0) stop("age must be positive")
x
}
# Helper (user-facing)
person <- function(name, age) {
validate_person(new_person(name, age))
}
alice <- person("Alice", 30)
#> Error in match.arg(name, person_field_names): 'arg' should be one of "given", "family", "role", "email", "comment"