In this tutorial you will learn about the new paradigm which R provides to its programmers. Other than function oriented programming, R also supports object oriented programming features line classes, objects, inheritance, overloading etc.

The Object Oriented R

Most R codes that you have gone through so far are functional programming based imperative programming. This means, functions are 1st class objects, but you typically end up with a data analysis script that executes one line at a single go. In some of the situation, it is valuable to use an object oriented programming (OOP) style. This means that data gets stored within a class all along the functions which are allowed to act on it. It is a superb tool to manage complexity in larger programs, which is particularly suited to GUI development.

Three systems are built into R

R has six different types of OOP systems. But only three of them are used for most of the applications. These are:

  • S3 is a lightweight scheme to overload any function i.e. calling a different name of the function depending upon the type of input parameter or the number of parameter).
  • S4 is a fully characteristic OOP system, but it is clumsy and tricky to debug. It is only used for legacy code.
  • Reference classes are the modern alternate for S4 classes.

What are Objects and Classes in R?

Programmers can perform object oriented programming in R. That is, everything in R is an object. So what an Object is? An object is a data structure which has some attributes and methods that can act upon its attributes.

On the other hand, classes are the outline or design for the object which encapsulates the data members along with the functions. You can think of class like a sketch or a prototype of anything which contains all the details.

Let's take an example of a university campus, where the departments, playground, stages, parking stand etc are its entity. Depending on these descriptions you may build the university campus and frame the design of that university.

Here university's campus is the object. As, many campus of such type can be constructed from a description, you can create many objects from a given class. An object is also termed as the instance of a class and the process of constructing this object is termed as 'instantiation'.

More on Classes and Objects of R

While the majority of programming languages have a single class system, R provides three class systems. These are:

S3, S4 and more recently Reference class systems (as listed earlier).

They possess their own characteristics and peculiarities and choosing one over another. Here is a simple example of how to use class in R:

> # make a list with necessary components
> g <- list (name = "Karl", age = 22, CGPA = 7.6)
> # name of the class
> class (g) <- "trainer"
> g

This will show the output as:

[1] "Karl"

[1] 22

[1] 7.6

[1] "trainer"

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram