Chapter 10. Compiled Code
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.
C++
To set up your package with Rcpp, run the following:
devtools::use_rcpp()
This will:
-
Create an src/ directory to hold your .cpp files.
-
Add
Rcppto theLinkingToandImportsfields 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
Workflow
Once you’re set up, the basic workflow should now be familiar:
-
Create a new C++ file, as illustrated ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access