Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create an S3 object of class "person".
R Programming
person <- list(name = "Alice", age = 30) class(person) <- [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the class name in quotes.
Using the wrong class name capitalization.
✗ Incorrect
To create an S3 object, assign the class attribute as a character string with the class name, here "person".
2fill in blank
mediumComplete the code to define a print method for the "person" class.
R Programming
print.person <- function(x) {
cat("Name:", x$name, "\nAge:", x$age, "\n")
}
p <- list(name = "Bob", age = 25)
class(p) <- "person"
print([1]) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Printing only a component like p$name instead of the whole object.
Trying to call the method name directly.
✗ Incorrect
To call the print method for the S3 object, pass the object itself to print().
3fill in blank
hardFix the error in this S3 method definition for "summary.person".
R Programming
summary.person <- function(object, ...) {
paste("Person:", object$name, "is", object$age, "years old")
}
p <- list(name = "Carol", age = 40)
class(p) <- "person"
summary([1]) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the class name instead of the object to summary().
Using the method name directly instead of summary().
✗ Incorrect
The summary function should be called with the object variable, here p, to dispatch the S3 method.
4fill in blank
hardFill both blanks to create an S3 object and check its class.
R Programming
obj <- list(value = 100) class(obj) <- [1] result <- class([2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the object name as a string when assigning class.
Checking class of a string instead of the object.
✗ Incorrect
Assign the class name as a string to obj, then check the class of obj itself.
5fill in blank
hardFill all three blanks to define a generic function and an S3 method, then call it.
R Programming
myfunc <- function(x) {
UseMethod([1])
}
myfunc.[2] <- function(x) {
paste("Called method for class", class(x))
}
obj <- list()
class(obj) <- [3]
myfunc(obj) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the generic function name as a string to UseMethod().
Not quoting the class name when assigning class.
Mismatch between class name and method suffix.
✗ Incorrect
UseMethod() needs the generic function name without quotes; method name uses class name; class assigned as string.