R is a high-level, expressive language. But that expressivity comes at a price: speed. That’s why incorporating a low-level, compiled language like C or C++ can powerfully complement your R code. Although C and C++ often require more lines of code (and more careful thought) to solve the same problem, they can be orders of magnitude faster than R.
Teaching you how to program in C or C++ is beyond the scope of the book. If you’d like to learn, start with C++ and the Rcpp package. Rcpp makes it easy to connect C++ to R. I’d also recommend using RStudio because it has many tools that facilitate the entire process. Start by reading my “High Performance Functions with Rcpp”, a freely available book chapter from Advanced R: it gently introduces the language by translating examples of familiar R code into C++. Next, check out the Rcpp book and the other resources listed in learning more.
To set up your package with Rcpp, run the following:
Create an src/ directory to hold your .cpp files.
Rcpp to the
Imports fields in the DESCRIPTION.
Set up a .gitignore file to make sure you don’t accidentally check in any compiled files (learn more about this in Chapter 13).
Tell you the two roxygen tags you need to add to your package:
#' @useDynLib your-package-name #' @importFrom Rcpp sourceCpp NULL
Once you’re set up, the basic workflow should now be familiar:
Create a new C++ file, as illustrated ...