

Problems that require advanced data structures and algorithms that R doesn’t provide. The overhead of calling a function in C++ is much lower than that in R. Recursive functions, or problems which involve calling functions millions of times.

Loops that can’t be easily vectorised because subsequent iterations depend on previous ones. Typical bottlenecks that C++ can address include: Rcpp provides a clean, approachable API that lets you write high-performance code, insulated from R’s arcane C API. While it is possible to write C or Fortran code for use in R, it will be painful by comparison. Rcpp makes it very simple to connect C++ to R.

This magic comes by way of the Rcpp package, a fantastic tool written by Dirk Eddelbuettel and Romain Francois (with key contributions by Doug Bates, John Chambers, and JJ Allaire). In this chapter you’ll learn how to improve performance by rewriting key functions in C++. You’ve used profiling to figure out where your bottlenecks are, and you’ve done everything you can in R, but your code still isn’t fast enough. You’re reading the first edition of Advanced R for the latest on this topic, see the Rewriting R code in C++ chapter in the second edition.
