Skip to Content
R Packages
book

R Packages

by Hadley Wickham
March 2015
Intermediate to advanced
202 pages
4h 23m
English
O'Reilly Media, Inc.
Content preview from R Packages

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 Rcpp to the LinkingTo and 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

Workflow

Once you’re set up, the basic workflow should now be familiar:

  1. 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.
Start your free trial

You might also like

R Packages, 2nd Edition

R Packages, 2nd Edition

Hadley Wickham, Jennifer Bryan
Nonparametric Hypothesis Testing: Rank and Permutation Methods with Applications in R

Nonparametric Hypothesis Testing: Rank and Permutation Methods with Applications in R

Stefano Bonnini, Livio Corain, Marco Marozzi, Luigi Salmaso

Publisher Resources

ISBN: 9781491910580Errata Page