The Rcpp package provides an API for seamlessly accessing, extending, and modifying R objects at the C++ level. Rcpp supports implementing R functions in C++ for high performance computing, and makes it easy to interface R with external libraries.
The RStudio IDE has a number of features that support working with Rcpp, including:
- Syntax highlighting for C / C++,
- Autocompletion for C / C++ classes, functions, and methods,
- Quick navigation to compiler errors and warnings,
- Integrated editor support for
Rcpp::sourceCpp()
, - Integrated tools for package development with Rcpp.
Getting Started
If you are new to Rcpp and / or the C++ programming language, the following resources provide a helpful introduction:
- Rcpp: Seamless R and C++ Integration
- Rcpp website: http://www.rcpp.org/
- Rcpp Quick Reference Guide
- High performance functions with Rcpp
- Introduction to Rcpp Attributes
- The Rcpp Gallery: http://gallery.rcpp.org/
System Prerequisites
You should also ensure that you have installed all necessary prerequisites for working with Rcpp. In particular, you will need a compiler toolchain to be able to compile C++ code.
Windows
Please ensure you have installed the relevant version of the RTools Toolchain. Different versions of R will use different toolchain versions; please ensure you have installed the version appropriate for the version(s) of R you are using.
macOS
Please ensure you have the latest version of the macOS Command Line Tools installed. These can be installed from a Terminal using:
xcode-select --install
Linux
The steps for installing the requisite build tools on Linux can differ depending on the operating system in use. Debian-based systems (e.g. Ubuntu) will need to run:
sudo apt install build-essential
Users on RedHat-based systems (e.g. Fedora) will need to run:
dnf group install "Development Tools"
Please note that instructions can also differ depending on the version of the Linux operating system installed -- if in doubt, please consult the official documentation for your system.
Exposing C++ Functions to R
Rcpp Attributes
The quickest way to get started is to use Rcpp to compile and export functions from a single C++ source file. This is done with the Rcpp::sourceCpp()
function, and makes use of Rcpp attributes, a high-level syntax for adding annotations to C++ source files.
The Rcpp::sourceCpp()
function parses a C++ file and looks for functions marked with the [[Rcpp::export]]
attribute. A shared library is then built and its exported functions are made available as R functions in the specified environment. For example, this source file contains an implementation of convolve (note the [[Rcpp::export]]
attribute in the comment above the function):
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector convolveCpp(NumericVector a, NumericVector b) {
int na = a.size(), nb = b.size();
int nab = na + nb - 1;
NumericVector xab(nab);
for (int i = 0; i < na; i++)
for (int j = 0; j < nb; j++)
xab[i + j] += a[i] * b[j];
return xab;
}
The addition of the export attribute allows us to do this from an R session:
> Rcpp::sourceCpp("convolve.cpp")
> convolveCpp(1:5, 5:1)
[1] 5 14 26 40 55 40 26 14 5
The convolveCpp()
function is made available in the R session, and it can readily accept R values to be used for the implemented convolution. The Rcpp attributes vignette contains more detailed documentation on using attributes.
Using sourceCpp
The RStudio C / C++ editing mode makes the same Source command typically available for R scripts available for C++ source files. You can access this command on the editing toolbar, or using the Ctrl+Shift+Enter keyboard shortcut.
The Source command will execute the sourceCpp()
function, and then monitor the results of the compilation for errors. If errors do occur, then the compiler error log is parsed into a navigable list:
Note that you can also check the Source on Save option to automatically source the C++ file every time it is saved. This variation will keep the keyboard focus within the editor whereas the Source command will move focus to the console.
Embedding R Code
Typically C++ and R code are kept in their own source files. However, it's often convenient to bundle code from both languages into a common source file that can be executed using single call to sourceCpp()
.
R code can be embedded within an C++ source file as part of a block comment of the form:
/*** R
# example R code calling our convolveCpp function
convolveCpp(5:1, 1:5)
*/
These R code blocks will automatically be executed after sourceCpp()
is invoked. This can be a useful way to test and iterate on C++ code, with the R code used to test and verify that your C++ code is behaving as expected.
Code Completion
RStudio includes comprehensive code completion for C++ based on libclang (the same underlying engine used by XCode and many other C / C++ tools):
Completions are provided for the C++ language, Rcpp, and any other libraries you have imported.
Diagnostics
As you edit C++ source files, RStudio uses libclang to scan your code looking for errors, incomplete code, or other conditions worthy of warnings or informational notes. For example, in the following image, the code includes a call to R::pnorm()
which expects 5 arguments to be passed, but the code only includes 4.:
Diagnostics alert you to the possibility of subtle problems and flag outright incorrect code as early as possible, substantially reducing iteration / debugging time.
Rcpp Package Development
Before developing packages with Rcpp, it's also important to have a firm grounding in the basics of R packages. We strongly recommend reading the R Packages book first. The Writing R Extensions manual is a helpful reference for more advanced topics in package development.
Creating a New Package
To create a new Rcpp package use the Create Project command (available on the Projects menu and on the global toolbar) and select the New Directory option. Then select R Package. On the following screen specify the project type as Package w/ Rcpp:
Note that if you have existing R scripts that you'd like to use as the basis for the new package you can specify them here and they'll be included in the new package.
Creating a new project in this fashion will result in a call to the Rcpp.package.skeleton()
function to generate the basic scaffolding for the package. If you prefer, you can also call this function directly then follow the instructions below for loading the generated package into RStudio.
Working with an Existing Package
To enable RStudio's package development tools for an existing Rcpp package you should do the following:
- Create a new RStudio Project associated with the package's directory.
- If the package DESCRIPTION file is located either in the project's root directory or at pkg/DESCRIPTION then it will be automatically discovered.
- Alternatively, go to Project Options : Build Tools, select "Package" as the project build tools type, and then specify the the subdirectory containing the package's DESCRIPTION file.
Adding Rcpp to an Existing Package
If you have an existing package which you'd like to add Rcpp to you should consult the Writing a package that uses Rcpp vignette. The most straightforward and reliable approach may be to simply create a new Package w/ Rcpp and then copy the existing packages code and other files into the new package's directory.
Building Packages
To work with packages in RStudio you use the Build pane, which includes a variety of tools for building and testing packages. While iteratively developing a package in RStudio, you typically use the Install command to re-build the package and reload it in a fresh R session:
The Install command performs several steps in sequence to ensure a clean and correct result:
- Calls
Rcpp::compileAttributes()
to generate code for exported C++ functions, - Unloads any existing version of the package (including shared libraries if necessary),
- Builds and installs the package using
R CMD INSTALL
, - Restarts the underlying R session to ensure a clean environment for re-loading the package,
- Reloads the package in the new R session by executing the
library()
function.
Note that you can also execute Install using a keyboard shortcut (Ctrl+Shift+B) as well as configure RStudio to automatically save open source files prior to rebuilding.
Custom options for building and checking packages can be specified using Project Options : Build Tools (see Customizing Package Build Options for more details).
Errors and Warnings
If compilation errors or warnings occur, they will be parsed and presented as a navigable list:
RStudio will automatically navigate to the first error in the list (you can subsequently view the other errors by double-clicking them). Note that you can switch between the error list view and the underlying build output using the toggle at the top-right of the Build pane.
Learning More
Once you've got a basic Rcpp package building within RStudio, you'll want to learn about the tools that can be used to test, document, and prepare packages for distribution. Please consult these articles for additional details:
- Building, Testing, and Distributing Packages
- Writing Package Documentation
- Customizing Package Build Options
Alternative Tools
While RStudio provides specific integrations for the Rcpp package, it is not the only option available for integrating C++ and R code. The cpp11 package provides similar tools for integrating R with C++, but has a slightly different philosophy towards the interface it exposes to R users. Please read the Get started with cpp11 reference guide for more details.
Comments
0 comments
Article is closed for comments.