📖 Scenario: You want to organize information about a simple bank account using an R6 class in R. This will help you keep track of the account owner's name and the current balance.
🎯 Goal: Build an R6 class called BankAccount with fields for owner and balance, a method to deposit money, and a method to get_balance that returns the current balance.
📋 What You'll Learn
Create an R6 class named BankAccount with fields owner and balance
Add a method deposit that adds an amount to balance
Add a method get_balance that returns the current balance
Create an instance of BankAccount with owner 'Alice' and balance 100
Deposit 50 into the account
Print the current balance using get_balance
💡 Why This Matters
🌍 Real World
Using R6 classes helps organize data and behavior together, like managing bank accounts or other objects with properties and actions.
💼 Career
Understanding R6 classes is useful for R programmers who want to write clean, reusable, and organized code in data science, software development, or automation.
Progress0 / 4 steps
1
Create the R6 class with fields
Write code to load the R6 package and create an R6 class called BankAccount with public fields owner and balance. Initialize owner and balance in the initialize method.
R Programming
Hint
Use R6Class to create the class. Define owner and balance as public fields and set them in initialize.
2
Add deposit and get_balance methods
Add two public methods to the BankAccount class: deposit that takes an amount and adds it to balance, and get_balance that returns the current balance.
R Programming
Hint
Define deposit to add amount to self$balance. Define get_balance to return self$balance.
3
Create an instance and deposit money
Create an object called account from the BankAccount class with owner set to 'Alice' and balance set to 100. Then call the deposit method on account to add 50.
R Programming
Hint
Use BankAccount$new("Alice", 100) to create the object. Use account$deposit(50) to add money.
4
Print the current balance
Use the get_balance method on the account object to print the current balance.
R Programming
Hint
Use print(account$get_balance()) to show the balance.
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
Step 1: Understand the role of R6Class()
R6Class() is used to define a class that can hold both data (fields) and functions (methods) together.
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().
Final Answer:
To create a class that groups data and functions together -> Option D
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?
B. methods = list(my_method = function() { print(self$field) })
C. method <- function() { print(self$field) }
D. methods = function(my_method) { print(self$field) }
Solution
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() {...}).
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.
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
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".
Step 2: Evaluate the greet method
The greet method returns paste0("Hello, ", self$name, "!"), which becomes "Hello, Anna!" for p.
Final Answer:
"Hello, Anna!" -> Option C
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
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.
Step 2: Verify other options
Class names can be uppercase, methods don't need explicit return, and initializing speed to 0 is valid.
Final Answer:
The method should use self$speed, not speed alone -> Option A
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?