Challenge - 5 Problems
R6 Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method call in R6 class
What is the output of the following R code?
R Programming
library(R6) Person <- R6Class("Person", public = list( name = NULL, initialize = function(name) { self$name <- name }, greet = function() { paste("Hello, my name is", self$name) } ) ) p <- Person$new("Alice") p$greet()
Attempts:
2 left
💡 Hint
Check how the initialize method sets the name and how greet accesses it.
✗ Incorrect
The initialize method sets self$name to 'Alice'. The greet method returns a string combining 'Hello, my name is' with self$name, which is 'Alice'.
🧠 Conceptual
intermediate1:30remaining
Understanding private fields in R6
Which statement about private fields in R6 classes is TRUE?
Attempts:
2 left
💡 Hint
Think about encapsulation and how private fields protect data.
✗ Incorrect
Private fields are defined inside the private list and are only accessible within the class methods, not from outside using $.
🔧 Debug
advanced2:00remaining
Identify the error in R6 method definition
What error will this code produce when run?
R Programming
library(R6) Counter <- R6Class("Counter", public = list( count = 0, increment = function() { count <- count + 1 } ) ) c <- Counter$new() c$increment() c$count
Attempts:
2 left
💡 Hint
Check how the increment method modifies the count variable.
✗ Incorrect
Inside increment, count <- count + 1 creates a local variable count instead of modifying self$count. So self$count remains 0.
📝 Syntax
advanced2:30remaining
Correct syntax for defining an active binding in R6
Which option correctly defines an active binding named 'double' that returns twice the value of private$x?
Attempts:
2 left
💡 Hint
Active bindings use a function with an optional argument to get or set values.
✗ Incorrect
Active bindings in R6 use a function with an optional argument 'value'. If value is missing, it returns the computed value; otherwise, it sets the underlying variable.
🚀 Application
expert3:00remaining
Predict the number of items in a list after method calls
Consider this R6 class that stores unique names in a list. After running the code below, how many items are in the list stored in the object?
R Programming
library(R6) UniqueNames <- R6Class("UniqueNames", private = list( names = list() ), public = list( add_name = function(name) { if (!(name %in% private$names)) { private$names <- c(private$names, name) } }, get_names = function() { private$names } ) ) obj <- UniqueNames$new() obj$add_name("Anna") obj$add_name("Bob") obj$add_name("Anna") obj$add_name("Cara") length(obj$get_names())
Attempts:
2 left
💡 Hint
Check how the add_name method checks for duplicates before adding.
✗ Incorrect
The add_name method adds a name only if it is not already in private$names. 'Anna' is added once, so total unique names are 3.