R Tutorial

Fundamentals of R

Variables

Input and Output

Decision Making

Control Flow

Functions

Strings

Vectors

Lists

Arrays

Matrices

Factors

DataFrames

Object Oriented Programming

Error Handling

File Handling

Packages in R

Data Interfaces

Data Visualization

Statistics

Machine Learning with R

R6 Classes

R6 is an R package that provides a modern way of using object-oriented programming (OOP) in R. Unlike R's traditional S3 and S4 class systems, R6 classes come with reference semantics, which means you can modify an object in place without creating a copy. Here's a basic tutorial on R6 classes:

1. Installing and Loading R6

Before you can use R6, you need to install and load it:

install.packages("R6")
library(R6)

2. Defining an R6 Class

To define an R6 class, use the R6Class() function. A class generally contains public fields (attributes) and methods (functions).

Person <- R6Class("Person",
  public = list(
    name = NULL,
    age = NULL,
    
    initialize = function(name = NA, age = NA) {
      self$name <- name
      self$age <- age
      cat("A new person has been initialized!\n")
    },
    
    set_age = function(value) {
      self$age <- value
    },
    
    print_age = function() {
      cat(self$name, "is", self$age, "years old.\n")
    }
  )
)

3. Creating an R6 Object

Once you have defined the class, you can create objects from it:

alice <- Person$new(name = "Alice", age = 30)

4. Accessing Fields and Methods

With R6, you can directly access fields and methods:

# Access field
cat("Name:", alice$name, "\n")

# Use method
alice$print_age()

# Modify age
alice$set_age(31)
alice$print_age()

5. Private Members

R6 allows for private fields and methods which are not directly accessible from outside the object:

BankAccount <- R6Class("BankAccount",
  private = list(
    balance = 0
  ),
  
  public = list(
    deposit = function(amount) {
      private$balance <- private$balance + amount
      cat("Deposited:", amount, "\n")
    },
    
    withdraw = function(amount) {
      private$balance <- private$balance - amount
      cat("Withdrew:", amount, "\n")
    },
    
    get_balance = function() {
      return(private$balance)
    }
  )
)

account <- BankAccount$new()
account$deposit(100)
account$withdraw(50)
cat("Balance:", account$get_balance(), "\n")

Note: The private balance field cannot be accessed directly from the outside.

6. Inheritance

R6 supports inheritance. One class can inherit fields and methods from another class:

Student <- R6Class("Student",
  inherit = Person,  # Inheriting from the Person class
  
  public = list(
    grade = NA,
    
    initialize = function(name, age, grade) {
      super$initialize(name, age)  # Call the initialize method of the parent class
      self$grade <- grade
    },
    
    print_grade = function() {
      cat(self$name, "has a grade of", self$grade, "\n")
    }
  )
)

bob <- Student$new(name = "Bob", age = 20, grade = "A")
bob$print_age()
bob$print_grade()

Conclusion

R6 provides a robust system for object-oriented programming in R. It offers features like encapsulation, inheritance, and reference semantics, making it a powerful tool for creating structured and modular programs in R.

  1. Introduction to R6 object-oriented programming in R:

    • Overview: Introduce the concept of R6 object-oriented programming.

    • Code:

      # Introduction to R6 object-oriented programming in R
      library(R6)
      
      Person <- R6Class(
        "Person",
        public = list(
          name = NULL,
          initialize = function(name) {
            self$name <- name
          },
          greet = function() {
            cat("Hello, I am", self$name, "\n")
          }
        )
      )
      
      john <- Person$new("John")
      john$greet()
      
  2. Creating and using R6 classes in R programming:

    • Overview: Demonstrate how to create and use R6 classes.

    • Code:

      # Creating and using R6 classes in R programming
      Animal <- R6Class(
        "Animal",
        public = list(
          name = NULL,
          initialize = function(name) {
            self$name <- name
          },
          speak = function() {
            cat("I am an animal named", self$name, "\n")
          }
        )
      )
      
      cat <- Animal$new("Cat")
      cat$speak()
      
  3. Inheritance and methods in R6 classes:

    • Overview: Illustrate inheritance and methods in R6 classes.

    • Code:

      # Inheritance and methods in R6 classes
      Dog <- R6Class(
        "Dog",
        inherit = Animal,
        public = list(
          bark = function() {
            cat("Woof! Woof!\n")
          }
        )
      )
      
      dog <- Dog$new("Buddy")
      dog$speak()
      dog$bark()
      
  4. R6 class attributes and methods examples:

    • Overview: Provide examples of attributes and methods in R6 classes.

    • Code:

      # R6 class attributes and methods examples
      Circle <- R6Class(
        "Circle",
        public = list(
          radius = NULL,
          initialize = function(radius) {
            self$radius <- radius
          },
          area = function() {
            pi * self$radius^2
          }
        )
      )
      
      my_circle <- Circle$new(radius = 5)
      area <- my_circle$area()
      cat("Area of the circle:", area, "\n")
      
  5. Encapsulation in R6 programming:

    • Overview: Showcase encapsulation in R6 programming.

    • Code:

      # Encapsulation in R6 programming
      Counter <- R6Class(
        "Counter",
        private = list(
          value = 0,
          increment = function() {
            self$value <- self$value + 1
          }
        ),
        public = list(
          get_value = function() {
            self$value
          },
          increment_and_get = function() {
            self$increment()
            self$value
          }
        )
      )
      
      my_counter <- Counter$new()
      my_counter$increment_and_get()
      
  6. Using R6 classes for modular code in R:

    • Overview: Demonstrate how R6 classes can contribute to modular code.

    • Code:

      # Using R6 classes for modular code in R
      Calculator <- R6Class(
        "Calculator",
        public = list(
          add = function(a, b) {
            a + b
          },
          multiply = function(a, b) {
            a * b
          }
        )
      )
      
      my_calculator <- Calculator$new()
      result <- my_calculator$add(3, 4)
      cat("Result of addition:", result, "\n")