Bird
Raised Fist0
R Programmingprogramming~20 mins

R6 classes in R Programming - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
R6 Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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()
AError: object 'name' not found
B"Hello, my name is NULL"
C"Hello, my name is Alice"
DNULL
Attempts:
2 left
💡 Hint
Check how the initialize method sets the name and how greet accesses it.
🧠 Conceptual
intermediate
1:30remaining
Understanding private fields in R6
Which statement about private fields in R6 classes is TRUE?
APrivate fields are global variables shared by all instances of the class.
BPrivate fields can be accessed directly from outside the object using $ operator.
CPrivate fields are automatically copied to public fields when the object is created.
DPrivate fields are defined inside the private list and cannot be accessed directly from outside the object.
Attempts:
2 left
💡 Hint
Think about encapsulation and how private fields protect data.
🔧 Debug
advanced
2: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
A0
B1
CError: object 'count' not found
DError: attempt to modify a locked binding
Attempts:
2 left
💡 Hint
Check how the increment method modifies the count variable.
📝 Syntax
advanced
2: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?
A
active = list(
  double = function(value) {
    if (missing(value)) private$x * 2 else private$x &lt;- value / 2
  }
)
B
active = list(
  double = function() {
    private$x * 2
  }
)
C
active = list(
  double = function(value) {
    private$x * 2
  }
)
D
active = list(
  double = function(value) {
    if (!missing(value)) private$x * 2 else private$x &lt;- value / 2
  }
)
Attempts:
2 left
💡 Hint
Active bindings use a function with an optional argument to get or set values.
🚀 Application
expert
3: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())
AError: object of type 'closure' is not subsettable
B3
C4
D2
Attempts:
2 left
💡 Hint
Check how the add_name method checks for duplicates before adding.

Practice

(1/5)
1. What is the main purpose of using R6Class() in R?
easy
A. To create plots and visualizations
B. To perform statistical tests on data
C. To import data from external files
D. To create a class that groups data and functions together

Solution

  1. Step 1: Understand the role of R6Class()

    R6Class() is used to define a class that can hold both data (fields) and functions (methods) together.
  2. Step 2: Compare with other options

    Creating plots and visualizations, performing statistical tests on data, and importing data from external files are unrelated tasks, not the purpose of R6Class().
  3. Final Answer:

    To create a class that groups data and functions together -> Option D
  4. Quick Check:

    R6Class() = class with data and methods [OK]
Hint: R6Class groups data and actions in one place [OK]
Common Mistakes:
  • Thinking R6Class is for data analysis only
  • Confusing R6Class with plotting functions
  • Assuming R6Class imports data
2. Which of the following is the correct way to define a method inside an R6 class?
easy
A. methods = { my_method <- function() { print(self$field) } }
B. methods = list(my_method = function() { print(self$field) })
C. method <- function() { print(self$field) }
D. methods = function(my_method) { print(self$field) }

Solution

  1. Step 1: Recall R6 method syntax

    Methods are defined inside a list with names as method names and values as functions, e.g., methods = list(name = function() {...}).
  2. Step 2: Check each option

    methods = list(my_method = function() { print(self$field) }) correctly uses a list with a named function. The other options do not follow the required list structure.
  3. Final Answer:

    methods = list(my_method = function() { print(self$field) }) -> Option B
  4. Quick Check:

    Methods = list of named functions [OK]
Hint: Methods must be in a named list inside R6Class [OK]
Common Mistakes:
  • Defining methods as a single function instead of list
  • Using assignment inside methods block incorrectly
  • Omitting the list() wrapper
3. What will be the output of this R code?
Person <- R6Class("Person",
  public = list(
    name = NULL,
    initialize = function(name) {
      self$name <- name
    },
    greet = function() {
      paste0("Hello, ", self$name, "!")
    }
  )
)
p <- Person$new("Anna")
p$greet()
medium
A. NULL
B. Error: object 'self' not found
C. "Hello, Anna!"
D. "Hello, name!"

Solution

  1. Step 1: Understand object creation and initialization

    The class Person has a field 'name' set during initialization with self$name <- name. The object p is created with name "Anna".
  2. Step 2: Evaluate the greet method

    The greet method returns paste0("Hello, ", self$name, "!"), which becomes "Hello, Anna!" for p.
  3. Final Answer:

    "Hello, Anna!" -> Option C
  4. Quick Check:

    p$greet() = "Hello, Anna!" [OK]
Hint: self$name holds the name; greet returns greeting string [OK]
Common Mistakes:
  • Expecting NULL because name is NULL initially
  • Confusing self with private or global variables
  • Thinking greet prints instead of returns
4. Identify the error in this R6 class definition:
Car <- R6Class("Car",
  public = list(
    speed = 0,
    accelerate = function() {
      speed <- speed + 10
    }
  )
)
c <- Car$new()
c$accelerate()
c$speed
medium
A. The method should use self$speed, not speed alone
B. The class name must be lowercase
C. The accelerate method must return speed explicitly
D. The speed field cannot be initialized to 0

Solution

  1. Step 1: Check variable usage inside method

    Inside accelerate(), speed <- speed + 10 updates a local variable speed, not the field. It should be self$speed to update the object's field.
  2. Step 2: Verify other options

    Class names can be uppercase, methods don't need explicit return, and initializing speed to 0 is valid.
  3. Final Answer:

    The method should use self$speed, not speed alone -> Option A
  4. Quick Check:

    Use self$ to access fields inside methods [OK]
Hint: Use self$ to access or change fields inside methods [OK]
Common Mistakes:
  • Forgetting self$ prefix for fields
  • Assuming local variable changes affect fields
  • Thinking class names must be lowercase
5. You want to create an R6 class BankAccount with a field balance starting at 0 and methods deposit(amount) and withdraw(amount). The withdraw method should not allow the balance to go below zero. Which code snippet correctly implements this?
hard
A. BankAccount <- R6Class("BankAccount", public = list( balance = 0, deposit = function(amount) { self$balance <- self$balance + amount }, withdraw = function(amount) { if (self$balance >= amount) { self$balance <- self$balance - amount } } ) )
B. BankAccount <- R6Class("BankAccount", public = list( balance = 0, deposit = function(amount) { balance <- balance + amount }, withdraw = function(amount) { balance <- balance - amount } ) )
C. BankAccount <- R6Class("BankAccount", public = list( balance = 0, deposit = function(amount) { self$balance <- amount }, withdraw = function(amount) { self$balance <- self$balance - amount } ) )
D. BankAccount <- R6Class("BankAccount", public = list( balance = 0, deposit = function(amount) { self$balance <- self$balance + amount }, withdraw = function(amount) { self$balance <- self$balance - amount } ) )

Solution

  1. Step 1: Check deposit method correctness

    Deposit should add amount to self$balance. Some options do this correctly; others do not use self$ or overwrite balance incorrectly.
  2. Step 2: Check withdraw method logic

    Withdraw must check if balance >= amount before subtracting to avoid negative balance. Only BankAccount <- R6Class("BankAccount", public = list( balance = 0, deposit = function(amount) { self$balance <- self$balance + amount }, withdraw = function(amount) { if (self$balance >= amount) { self$balance <- self$balance - amount } } ) ) has this check.
  3. Final Answer:

    The code snippet with self$balance updates and balance check before withdrawal -> Option A
  4. Quick Check:

    Use self$ and check balance before withdrawal [OK]
Hint: Withdraw must check balance before subtracting [OK]
Common Mistakes:
  • Not using self$ to update balance
  • Overwriting balance instead of adding
  • Allowing negative balance without check
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard