Better Programming

Advice for programmers.

Follow publication

R and C++ Together: An Introduction to Rcpp

Achieving high performance in R

Uğurcan Demir
Better Programming
Published in
4 min readAug 22, 2022

--

Photo by Markus Spiske on Unsplash

R is a beautiful programming language, and it has many strengths.

Unfortunately, performance is not one of them. Although R is readable and versatile, it is not known for its performance. Being a dynamically typed and interpreted language, R is prone to all of the inadequacies that the languages which fall into these categories have. The performance of a programming language is determined by many factors. But the two facts are that every time we run an R script, a messenger called “Interpreter” conveys and translates code. And every time we run an R script, the type of every variable specified during the translation process, called “Run Time,” is enough to make R a slow programming language.

The good news is that there are many antidotes to overcome the difficulty of slowness. We can gain a dramatic performance increase with the right set of tools. The most legitimate way is to get help from a low-level programming language. This article aims to get you started with rewriting the bottlenecks of your code in C++.

What Is C++, and Why Does It Matter?

C++ is one of the world’s most powerful programming languages, and it is everywhere. Thousands of devices we use every day run on C++. It is the successor of another well-known programming language called C.

To give a little bit of history, C was created in 1972 by Dennis Ritchie. At the time, C caused a revolution in the computing world, but over time, users of it realized that it lacked some of the finest properties other languages had had. One of those was object-oriented programming. As a result of this realization Bjarne Stroustrup, a Danish computer scientist, created C++ in 1985. C++ extended the capabilities of C and added an object-oriented paradigm. In fact, C++ just means “C with classes.”

For decades, C++ has had a fundamental role in the programming world and influenced almost every part of it. Luckily for us R programmers, C++ has a very close connection with R, so we can benefit from this connection and empower our R projects. As you go through your R journey, you will be amazed at what a pinch of C++ code can do in an R project.

The Old School Way To Extend R

Traditionally, R has provided several built-in tools to interface with two other languages, C and Fortran. With Fortran being obsolete, C has been the go-to language for R. For that purpose, standard R provides two functions to interface R with C: .C() and .Call(). However, this traditional way is so outdated and painful. So, we will look at a much more modern and user-friendly way and not mention these two functions in our article.

Rcpp

The piece of heaven that helps us beautify our R project with C++ is a package called Rcpp. Rcpp is developed by a team led by Dirk Eddelbuettel, another fellow econometrician from Canada. Rcpp provides an interface between R and C++, and this package is so powerful that an entire book, “Seamless R and C++ Integration with Rcpp,” has been published by Springer.

You can get started by running the code below:

library(Rcpp)

Turning C++ Into R Within the Script

The easiest and quickest way to improve the performance of an R script is to change problematic parts of the script and rewrite them in C++. Rcpp::cppFunction() function is just the thing you need. It’s neat and convenient. cppFunction() takes a C++ function and converts it into an R function. All you have to do is to pass your C++ function as a string, and it will do the rest.

Rcpp::cppFunction()

For the sake of simplicity, we will write two additional functions: one in R, and the other in C++. These will illustrate the usage of cppFunction().

Below you can find the additional function written in R:

addition_r <- function(a , b) {
a + b
}
addition_r(5 , 10)## [1] 15

Now we write the same function in C++ and use it as if we’d written it in R.

addition_cpp <- cppFunction('int additioncpp(int a, int b) {
int sum = a + b ;
return sum;
}')
addition_cpp(5 , 10)## [1] 15

It is ridiculously simple and can save you huge time.

Although it is tempting to use quick and dirty methods like the above for scripts of a couple of hundred lines, it is not the most desirable way to build an entire project. Most R projects are not a script but consist of tens of scripts. In a case like that, we may wish to import an entire C++ file into our R session. This is the subject of the next topic.

Using Separate C++ Files in R Projects

To use the parts of a separate C++ file, we benefit Rcpp::sourceCpp() function.

Rcpp::sourceCpp()

And the trick is, for each function you want to import from the C++ file, you must add this indicator: // [[Rcpp::export]].

Below, you can see an example of what a ready-to-be-imported C++ file should look like. It is saved as arithmetic.cpp:

Now, the code below imports the prespecified content of arithmetic.cpp.

sourceCpp("C:/Users/ugurc/Desktop/Medium Blog/High Performance in R/arithmetic.cpp")subtractioncpp(a = 10 , b = 5)## [1] 5multiplicationcpp(a = 10 , b = 5)## [1] 50

Conclusion

Every day around the world, R developers create thousands of wonderful projects, thousands of applications run R code, and millions of dollars of industries use R. Whenever this beautiful language comes short, we deploy various solutions.

Applying a low-level language is by far the sharpest solution to those shortcomings. Now with the information in this article, you can recreate your R application by rewriting its bottlenecks in C++.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Uğurcan Demir
Uğurcan Demir

Written by Uğurcan Demir

Statistician/Econometrician. Software enthusiast.

No responses yet

Write a response