0
0
R Programmingprogramming~30 mins

R6 classes in R Programming - Mini Project: Build & Apply

Choose your learning style9 modes available
Create and Use an R6 Class in R
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use print(account$get_balance()) to show the balance.