Classes in R: Object-Oriented Programming Made Simple

 Classes In R Programming

While most programming languages have a single class system, R has three class systems:
  • S3 Class
  • S4 Class
  • Reference Class
The original R Structure for classes, known as S3, is still the dominant class paradigm in R use today. Indeed, most of R's own built-in classes are of the S3 type. 

CLASSES IN R
CLASSES IN R PROGRAMMING

An S3 class of a list, with a class name attribute and dispatch capability added.

1) S3 Class:

An S3 class in R is a simple way to create objects that belong to a certain type. It doesn't require a lot of formal setup. You create an S3 object by assigning it a "class" label, and you can make functions behave differently based on that class. 

For example, a print() function can be made to show different outputs for different classes. S3 is easy to use because it’s very flexible, but this also means you need to be careful when working with it to avoid mistakes.

Example :

# Create an S3 object of class 'person'

person <- list(name = "John", age = 30)
class(person) <- "person"

# Define a print method for the 'person' class

print.person <- function(x) {
  cat("Name:", x$name, "\n")
  cat("Age:", x$age, "\n")
}

# Test the 'print' method

print(person)

2) S4 Class :

In R programming, an S4 class is a more formal and rigorous object-oriented system compared to S3. S4 classes allow you to define objects with specific slots (attributes) and enforce strict rules about what an object can contain.

With S4, you explicitly define a class using the setClass() function, specifying its slots (attributes) and types. 

Methods for S4 classes are also formally defined with the setMethod() function, which ensures that they match the class definition. 

The S4 system supports inheritance and provides more robust error checking, making it suitable for larger, more complex projects where data integrity is critical. The new() function is used to create an object of the class "person".

Example :

# Define an S4 class called 'person'

setClass(
  "person",
  slots = list(
    name = "character",
    age = "numeric"
  )
)

# Create an object of class 'person' using the 'new' function

john <- new("person", name = "John", age = 30)

# Define a method to show a summary for 'person' objects

setMethod(
  "show",
  "person",
  function(object) {
    cat("Name:", object@name, "\n")
    cat("Age:", object@age, "\n")
  }
)

# Print the object to use the show method

john
30

3) Reference class: 

In R programming, a Reference Class (or R5 class) is an object-oriented system that supports mutable objects, meaning you can modify an object's fields without creating a new object. Reference classes provide functionality similar to classes in other programming languages like Python or Java.

To create a reference class, you use the `setRefClass()` function. Unlike S3 and S4, reference class objects have fields (attributes) and methods (functions) that can modify those fields directly. This is particularly useful for situations where you need objects that change state over time, such as in simulations or interactive applications.

Example :
# Define a reference class called 'Person' Person <- setRefClass( "Person", fields = list( name = "character", age = "numeric" ), methods = list( greet = function() { cat("Hello, my name is", name, "and I am", age, "years old.\n") }, have_birthday = function() { age <<- age + 1 cat("Happy Birthday! I am now", age, "years old.\n") } ) ) # Create an instance of the 'Person' class john <- Person$new(name = "John", age = 30) # Call methods on the object john$greet() john$have_birthday() john$greet()

Explanation

  1. Define a Reference Class: The setRefClass() function is used to define a class called "Person" with two fields: name and age. It also has two methods: greet() to introduce the person and have_birthday() to increment their age.
  2. Create an Object: We create an instance of the class "Person" called john using the $new() function, specifying name as "John" and age as 30.
  3. Call Methods: We use $greet() to display a greeting and $have_birthday() to increase John's age by 1. The modified age is reflected without creating a new object, demonstrating the mutability of reference classes.
These are the three types of class in R programming. Based on the these types of classes we can do the further operations in classes.

Writing inheritance using S classes:

In R, inheritance can be implemented using S3, S4, and Reference Classes. Inheritance allows one class to extend another, enabling code reuse and shared behavior between related classes.

S3 Inheritance Example

S3 inheritance is informal, relying on setting multiple classes for an object.

# Define a 'person' class

person <- list(name = "John", age = 30)
class(person) <- "person"

# Define an 'employee' class that inherits from 'person'

employee <- list(name = "Alice", age = 28, job_title = "Analyst")
class(employee) <- c("employee", "person")

# Define print methods for each class

print.person <- function(x) {
  cat("Name:", x$name, "\n")
  cat("Age:", x$age, "\n")
}

print.employee <- function(x) {
  cat("Name:", x$name, "\n")
  cat("Age:", x$age, "\n")
  cat("Job Title:", x$job_title, "\n")
}

# Test the print method for employee

print(employee)

In this example, the `"employee"` class inherits from `"person"` by using a class vector (`class(employee) <- c("employee", "person")`). When you call `print(employee)`, it first looks for a method for `"employee"`; if it doesn't find one, it will look for a method for `"person"`.

S4 Inheritance Example

S4 inheritance is more formal, and classes are explicitly defined using `contains`.

# Define an S4 class called 'person'

setClass(
  "person",
  slots = list(
    name = "character",
    age = "numeric"
  )
)

# Define an S4 class called 'employee' that inherits from 'person'

setClass(
  "employee",
  slots = list(
    job_title = "character"
  ),
  contains = "person"
)

# Create an object of class 'employee'

alice <- new("employee", name = "Alice", age = 28, job_title = "Analyst")

# Define a method to show a summary for 'employee' objects

setMethod(
  "show",
  "employee",
  function(object) {
    cat("Name:", object@name, "\n")
    cat("Age:", object@age, "\n")
    cat("Job Title:", object@job_title, "\n")
  }
)

# Print the object

alice

In this S4 example, the class `"employee"` inherits from `"person"` using the `contains` argument in `setClass()`. The `show` method is defined specifically for `"employee"` objects to display their properties.

 Reference Class Inheritance Example

Reference classes also support inheritance by defining a new class that contains the parent class.

# Define a reference class called 'Person'

Person <- setRefClass(
  "Person",
  fields = list(
    name = "character",
    age = "numeric"
  ),
  methods = list(
    greet = function() {
      cat("Hello, my name is", name, "and I am", age, "years old.\n")
    }
  )
)

# Define a reference class called 'Employee' that inherits from 'Person'

Employee <- setRefClass(
  "Employee",
  contains = "Person",
  fields = list(
    job_title = "character"
  ),
  methods = list(
    greet = function() {
      cat("Hello, my name is", name, ", I am", age, "years old, and I work as a", job_title, ".\n")
    }
  )
)

# Create an instance of the 'Employee' class

alice <- Employee$new(name = "Alice", age = 28, job_title = "Analyst")

# Call methods on the object

alice$greet()

In this example, `"Employee"` inherits from `"Person"` using `contains = "Person"`. The `greet` method is overridden in `"Employee"` to include the job title.

Post a Comment

0 Comments