0
0
R Programmingprogramming~5 mins

R6 classes in R Programming

Choose your learning style9 modes available
Introduction

R6 classes help you organize your code by grouping data and actions together. They make your programs easier to understand and reuse.

When you want to create objects that keep their own data and behavior.
When you need to model real-world things like cars, people, or bank accounts in your code.
When you want to write code that is easier to maintain and extend later.
When you want to avoid repeating the same code in many places.
When you want to keep track of changing information inside an object.
Syntax
R Programming
library(R6)

MyClass <- R6Class(
  "MyClass",
  public = list(
    field1 = NULL,
    initialize = function(value) {
      self$field1 <- value
    },
    method1 = function() {
      print(paste("Value is", self$field1))
    }
  )
)

R6Class() creates a new class.

public lists fields and methods accessible from outside.

Examples
This example creates a Person class with a name and a greeting method.
R Programming
library(R6)

Person <- R6Class(
  "Person",
  public = list(
    name = NULL,
    initialize = function(name) {
      self$name <- name
    },
    greet = function() {
      print(paste("Hello, my name is", self$name))
    }
  )
)
This example creates a Counter class that can increase and return its count.
R Programming
library(R6)

Counter <- R6Class(
  "Counter",
  public = list(
    count = 0,
    increment = function() {
      self$count <- self$count + 1
    },
    get_count = function() {
      return(self$count)
    }
  )
)
Sample Program

This program creates a Car class with a brand and speed. It can speed up by a given amount. We make a Toyota car and speed it up twice.

R Programming
library(R6)

Car <- R6Class(
  "Car",
  public = list(
    brand = NULL,
    speed = 0,
    initialize = function(brand) {
      self$brand <- brand
    },
    accelerate = function(amount) {
      self$speed <- self$speed + amount
      print(paste(self$brand, "is going", self$speed, "km/h"))
    }
  )
)

my_car <- Car$new("Toyota")
my_car$accelerate(30)
my_car$accelerate(20)
OutputSuccess
Important Notes

Use self$ to access fields and methods inside the class.

Initialize fields in the initialize method to set starting values.

R6 classes are useful for keeping data and functions together like real objects.

Summary

R6 classes group data and actions in one place.

Use R6Class() to create a class with fields and methods.

Create objects with $new() and use self$ inside methods.