0
0
R Programmingprogramming~10 mins

S3 object system in R Programming - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
A"Person"
Blist
Cperson
D"person"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the class name in quotes.
Using the wrong class name capitalization.
2fill in blank
medium

Complete 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'
Ap
Bp$name
Cperson
Dprint.person
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.
3fill in blank
hard

Fix 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'
Aobject
Bp
Cperson
Dsummary.person
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the class name instead of the object to summary().
Using the method name directly instead of summary().
4fill in blank
hard

Fill 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'
A"myclass"
Bobj
C"obj"
Dvalue
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.
5fill in blank
hard

Fill 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'
A"myfunc"
Bmyclass
C"myclass"
Dmyfunc
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.