

You’ll learn how C++ differs from R, and what the key scalar, vector, and matrix classes are called. Getting started with C++ teaches you how to write C++ by converting simple R functions to their C++ equivalents. You may also enjoy Dirk Eddelbuettel’s Seamless R and C++ integration with Rcpp, which goes into much greater detail into all aspects of Rcpp. For more advanced topics, the Effective C++ series by Scott Meyers is popular choice. Many good tutorials and references are freely available, including and. A working knowledge of C++ is helpful, but not essential. We won’t spend much time on advanced features like object oriented programming or templates because the focus is on writing small, self-contained functions, not big programs. The aim of this chapter is to discuss only those aspects of C++ and Rcpp that are absolutely necessary to help you eliminate bottlenecks in your code. Through the standard template library (STL), C++ has efficient implementations of many important data structures, from ordered maps to double-ended queues. 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.
