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 needed
cat("====================\n")
cat("Result:", result, "\n")
cat("====================\n")

Code explanation

  • Line 1: Installs the necessary Rcpp packages. This line is added as a comment because the Rcpp packages are already installed.

  • Line 2: Includes the Rcpp library in the code.

  • Lines 3–6: Writes the function that needs to be added in R in C++.

  • Line 7: Passes values to the divide function and stores the output in the result variable.

  • Lines 9–11: Prints cat as 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():

  1. Create a .cpp file.

  2. Include the Rcpp header file and namespace in the code.

#include <Rcpp.h>
using namespace Rcpp;
Including Rcpp header file and namespace
  1. 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.

  2. Create an R file, install packages, and use the Rcpp library. We have not included install.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)
Installing necessary Rcpp packages and including Rcpp library
  1. Give a .cpp file's path in the sourceCpp() function.

Code example

Let's execute the code to increase our understanding of sourceCpp().

main.r
numberCheck.cpp
#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.cpp file:

    • 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 the main.r file.

    • Lines 5–15: A boolean function that returns TRUE when the number is positive and false when it is negative.

    • Line 17–27: The boolean function, evenOdd(int num), returns TRUE when the number is even and FALSE when it is odd.

  • In the main.r file:

    • Line 1: Installs the necessary Rcpp packages. This line is added as a comment in the code above as the Rcpp packages are already installed.

    • Line 2: Includes the Rcpp library in the code.

    • Line 3: Passes the path of checkNumber.cpp in sourceCpp().

    • Line 5: Calls the C++ function, positiveNegative(), and passes the num number as an argument.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved