How to write C++ code in R
R is a programming language used for computational tasks and graphical representation of data. Despite its many useful features, one drawback of R is its performance. To boost performance, we often integrate other languages with R, such as C++, to enhance the computational speed of R due to its low-level memory manipulation and high-speed execution.
Rcpp
Rcpp is an R package used for hassle-free integration of C++ with R. Using Rcpp, we can rewrite all our key functions in C++ to perform computationally intensive tasks faster.
How to use Rcpp
To get started, we first install the Rcpp packages. For this, we need to include the following statement in our code:
install.packages("Rcpp")
Next, we need to include the following statement that helps to execute the Rcpp code:
library(Rcpp)
Mainly, we use two methods to write C++ code in R. We can either use cppFunction() directly in the R code, or use sourceCpp() to include a separate .cpp file.
Using cppFunction()
Using cppFunction() is more widespread and helpful than creating a separate .cpp file. With this approach, we can rewrite time-taking R functions in C++ and increase our code's performance.
Code example
Let's execute an example code for better understanding.
#install.packages("Rcpp")library(Rcpp)cppFunction('int divide(int dividend, int divisor) {int div = dividend/divisor;return div;}')result <- divide(4, 2)# Print the result if neededcat("====================\n")cat("Result:", result, "\n")cat("====================\n")
Code explanation
Line 1: Installs the necessary
Rcpppackages. This line is added as a comment because theRcpppackages are already installed.Line 2: Includes the
Rcpplibrary in the code.Lines 3–6: Writes the function that needs to be added in R in C++.
Line 7: Passes values to the
dividefunction and stores the output in theresultvariable.Lines 9–11: Prints
catas the output in a formatted manner.
Using sourceCpp()
Although the cppFunction() method is easier, it can make our code clustered. Therefore, it is recommended to write C++ code in separate files for extensive projects. These .cpp files can then be included in R code using sourceCpp(). This method keeps our code organized in separate files and increases reusability.
Use the following steps to integrate C++ in R using sourceCpp():
Create a
.cppfile.Include the
Rcppheader file and namespace in the code.
#include <Rcpp.h>using namespace Rcpp;
Write the
//[[Rcpp::export]]attribute before the C++ function that we want to use in R. The//[[Rcpp::export]]attribute controls which function should be exported from C++ to R. So, it is added before the C++ function we want to make available in R.Create an R file, install packages, and use the
Rcpplibrary. We have not includedinstall.packages("Rcpp")in the code example below, as all the packages are already installed. However, for running the code locally, you must always install packages with:
install.packages("Rcpp")library(Rcpp)
Give a
.cppfile's path in thesourceCpp()function.
Code example
Let's execute the code to increase our understanding of sourceCpp().
#include <Rcpp.h>using namespace Rcpp;//[[Rcpp::export]]bool positiveNegative(int num){if(num>0){return 1;}else{return 0;}}bool evenOdd(int num){if(num%2==0){return 1;}else{return 0;}}
Code explanation
In the
numberCheck.cppfile:Line 4: The
//[[Rcpp::export]]attribute allows the function to be used in R code. In this example,positiveNegative(int num)can be used in themain.rfile.Lines 5–15: A boolean function that returns
TRUEwhen the number is positive and false when it is negative.Line 17–27: The boolean function,
evenOdd(int num), returnsTRUEwhen the number is even andFALSEwhen it is odd.
In the
main.rfile:Line 1: Installs the necessary
Rcpppackages. This line is added as a comment in the code above as theRcpppackages are already installed.Line 2: Includes the
Rcpplibrary in the code.Line 3: Passes the path of
checkNumber.cppinsourceCpp().Line 5: Calls the C++ function,
positiveNegative(), and passes thenumnumber as an argument.
Free Resources