R S4 Class

S4 class is similar to S3 but is more formal and improvement over the S3 class. There are two major differences between S3 and S4.

S4 has formal class definitions, which define the representation and inheritance for each class, and has special helper functions for defining generics and methods. S4 class also has multiple dispatches, which means that generic functions can pick methods based on the class of any number of arguments, not just one.

Defining S4 Class

S4 class is defined using the setclass() function.

In terms of R programming, member variables are also called slots. In the definition of class, we need to set the name and slots along with the class of the slot.

setClass(“student”, slots=list(name=”character”, age=”numeric”, GPA=”numeric”))

In the above example, student is the class and name, age and GPA are the slots.

Create S4 Object

To create an S4 object we have to use the new() function.

Example:

Output:

We can check the created object is an S4 object or not by using isS4() function:

Create an S4 Object Using Generator Function

The setClass() function returns a generator function.

Usually, this generator function has the same name as the class name. This function can be used to create new objects. It will act as a constructor.

Example:

Let’s see an example to create S4 object using generator function:

Output:

Access and Modify Slot

@ is used to access the slot of an object.

Example:

Modifying Slot Directly

We can modify the slot through reassignment.

Example:

Output:

An object of class “student”

Modifying Slots Using slot() Function

We can access or modify the slots of an object through slot() also.

Methods and Generic Functions

Like S3 class, methods of S4 class also belong to generic functions rather than the class itself.

The showMethod() function is used to list all the generic functions and methods available in S4.

Example:

Like print() generic function of S3 class, S4 class has show() generic function.

List all Methods of a Generic Function

To list all methods of generic function S4 class has showMethod(show) function.

Create Our Own Method

We can create our own method using the setMethod() function.

Example:

We can create our own class method for the show() generic as follows:

Output: