Reader small image

You're reading from  Learning R Programming

Product typeBook
Published inOct 2016
Reading LevelBeginner
PublisherPackt
ISBN-139781785889776
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Kun Ren
Kun Ren
author image
Kun Ren

Kun Ren has used R for nearly 4 years in quantitative trading, along with C++ and C#, and he has worked very intensively (more than 8-10 hours every day) on useful R packages that the community does not offer yet. He contributes to packages developed by other authors and reports issues to make things work better. He is also a frequent speaker at R conferences in China and has given multiple talks. Kun also has a great social media presence. Additionally, he has substantially contributed to various projects, which is evident from his GitHub account: https://github.com/renkun-ken https://cn.linkedin.com/in/kun-ren-76027530 http://renkun.me/ http://renkun.me/formattable/ http://renkun.me/pipeR/ http://renkun.me/rlist/
Read more about Kun Ren

Right arrow

Chapter 10. Object-Oriented Programming

In the previous chapter, you learned how functional programming and metaprogramming make it possible to customize the behavior of functions. We can create a function within a certain context, which is called a closure. We can also use higher order functions by passing functions around just like other objects.

In this chapter, you will learn how to customize the behavior of objects by walking into the world of object-oriented programming. R provides several different object-oriented systems to work with. At first glance, they look quite different from the object-oriented systems in other programming languages. However, the idea is mostly the same. I will briefly explain the concept of class and method of objects, and show you how they can be useful in unifying the way we work with data and models.

We will cover the following topics at the beginner level in the subsequent sections:

  • The idea of object-oriented programming

  • S3 system

  • S4 system

  • Reference class...

Introducing object-oriented programming


If you are a developer from programming languages such as Java, Python, C++, C#, you should feel familiar with the object-oriented style of coding. However, if you are not familiar with any other object-oriented programming languages, you will probably be puzzled by this term, as it sounds a bit abstract. However, don't worry; this is much easier to understand than it looks if we think about the core of programming.

When we talk about programming, we are actually talking about using programming tools to solve problems. Before solving the problem, we need to model the problem first. Traditionally, we usually figured out an algorithm that takes several steps to solve a numeric computing problem. Then, we wrote some procedural code to implement the algorithm. For example, most statistical algorithms are implemented in a procedural style, that is, by transforming the input into the output according to the theory, step by step.

However, many problems are...

Working with the S3 object system


The S3 object system in R is a simple, loose, object-oriented system. Every basic object type has an S3 class name. For example, integernumericcharacterlogicallist,  data.frame, and so on are all S3 classes.

For example, the type of vec1 class is double, which means the internal type or storage mode of vec1 is double floating numbers. However, its S3 class is numeric:

vec1 <- c(1, 2, 3) 
typeof(vec1) 
## [1] "double" 
class(vec1) 
## [1] "numeric" 

The type of data1 class is list, which means the internal type or storage mode of data1 is a list, but its S3 class is data.frame:

data1 <- data.frame(x = 1:3, y = rnorm(3)) 
typeof(data1) 
## [1] "list" 
class(data1) 
## [1] "data.frame" 

In the following sections, we'll explain the difference between the internal type of an object and its S3 class.

Understanding generic functions and method dispatch

As we mentioned earlier in this chapter, a class can...

Working with S4


In the previous section, we introduced the S3 system. Unlike the object-oriented systems in most other programming languages, the S3 system is much less strict than a system in which classes are defined with a fixed structure and certain method dispatch as the program compiles. When we define an S3 class, almost nothing can be sure. We can not only add or remove methods of the class at any time but also insert or delete data elements from the object as we wish. In addition, S3 only supports single dispatch, that is, methods are chosen according to the class of only one argument, mostly the first argument.

Then, R introduces a more formal and stricter object-oriented system, S4. This system allows us to define formal classes with pre-specified definition and inheritance structure. It also supports multiple dispatch, that is, methods are chosen according to the classes of multiple arguments.

In this section, you will learn how to define S4 classes and methods.

Defining S4 classes...

Working with the reference class


There is also a class system that has reference semantics. It is more like the class system in other object-oriented programming languages.

First, to define a reference class (RC), we supply a class definition to setRefClass(). Unlike the S4 class system where we use new() to create an instance, setRefClass() returns an instance generator. For example, we define a class named Vehicle, which has two fields: a numeric position and a numeric distance. We store the instance generator to a variable named Vehicle:

Vehicle <- setRefClass("Vehicle",  
  fields = list(position = "numeric", distance = "numeric")) 

To create an instance, we use Vehicle$new to create new instances of the Vehicle class:

car <- Vehicle$new(position = 0, distance = 0) 

Unlike S4, the fields of RC are not slots, so we can use $ to access them:

car$position 
## [1] 0 

Each instance we create with Vehicle$new is an object of reference semantics. It behaves like a...

Working with R6


An enhanced version of RC is R6, a package that implements a more efficient reference class that supports public and private fields and methods, and some other powerful features.

Run the following code to install the package:

install.packages("R6") 

The R6 class allows us to define classes that are even more like popular object-oriented programming languages. The following code is an example where we define the Vehicle class. It has some public fields and methods for users and some private fields and methods for internal use:

library(R6) 
Vehicle <- R6Class("Vehicle",  
  public = list( 
    name = NA, 
    model = NA, 
    initialize = function(name, model) { 
      if (!missing(name)) self$name <- name 
      if (!missing(model)) self$model <- model 
    }, 
    move = function(movement) { 
      private$start() 
      private$position <- private$position + movement 
      private$stop() 
  ...

Summary


In this chapter, you learned the basic concepts of object-oriented programming: class and methods and how they are connected by generic functions in R through method dispatch. You learned how to create S3, S4, RC, and R6 classes and methods. These systems share similar ideas but are distinct in implementation and usage. Hadley Wickham gives some nice suggestions in picking a system (http://adv-r.had.co.nz/OO-essentials.html#picking-a-system).

After getting familiar with R's most important features, we will discuss more practical topics in the subsequent chapters. In the next chapter, you will learn about the packages and techniques used to access popular databases. You will gain necessary knowledge and techniques to connect R to relational databases such as SQLite and MySQL as well as the upcoming non-relational databases such as MongoDB and Redis.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning R Programming
Published in: Oct 2016Publisher: PacktISBN-13: 9781785889776
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at ₹800/month. Cancel anytime

Author (1)

author image
Kun Ren

Kun Ren has used R for nearly 4 years in quantitative trading, along with C++ and C#, and he has worked very intensively (more than 8-10 hours every day) on useful R packages that the community does not offer yet. He contributes to packages developed by other authors and reports issues to make things work better. He is also a frequent speaker at R conferences in China and has given multiple talks. Kun also has a great social media presence. Additionally, he has substantially contributed to various projects, which is evident from his GitHub account: https://github.com/renkun-ken https://cn.linkedin.com/in/kun-ren-76027530 http://renkun.me/ http://renkun.me/formattable/ http://renkun.me/pipeR/ http://renkun.me/rlist/
Read more about Kun Ren