0
0
R Programmingprogramming~10 mins

R6 classes 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 a new R6 class named 'Person'.

R Programming
Person <- R6Class([1] = "Person")
Drag options to blanks, or click blank then click option'
Aclassname
Bid
Cname
Dclass
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'class' or 'name' instead of 'classname' causes errors.
2fill in blank
medium

Complete the code to add a public method 'greet' that prints 'Hello!'.

R Programming
Person <- R6Class(classname = "Person",
  public = list(
    greet = function() {
      print([1])
    }
  )
)
Drag options to blanks, or click blank then click option'
A"Hello!"
B'Hi!'
CHello!
D'Hello'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes or using single quotes without exclamation mark.
3fill in blank
hard

Fix the error in the code to correctly initialize a field 'name' with a default value 'John'.

R Programming
Person <- R6Class(classname = "Person",
  public = list(
    name = [1],
    initialize = function(name = "John") {
      self$name <- name
    }
  )
)
Drag options to blanks, or click blank then click option'
ANA
B"John"
CNULL
Dname
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the field directly to a string causes errors before initialize runs.
4fill in blank
hard

Fill both blanks to add a private field 'age' and a public method 'get_age' that returns it.

R Programming
Person <- R6Class(classname = "Person",
  private = list(
    [1] = NULL
  ),
  public = list(
    get_age = function() {
      return(private$[2])
    }
  )
)
Drag options to blanks, or click blank then click option'
Aage
Cname
Dage_value
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the private field and in the method causes errors.
5fill in blank
hard

Fill all three blanks to create a method 'set_name' that updates the 'name' field and prints confirmation.

R Programming
Person <- R6Class(classname = "Person",
  public = list(
    name = NULL,
    set_name = function(new_name) {
      self$[1] <- [2]
      print(paste("Name set to", [3]))
    }
  )
)
Drag options to blanks, or click blank then click option'
Aname
Bnew_name
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up variable names or forgetting 'self$' causes errors.