Statisfaction

Speed up your R code with C++

Posted in Geek, R by Pierre Jacob on 4 February 2011

Hi again,

Recently, Julyan blogged about allocating memory first before modifying R objects. That’s a very useful trick that applies to most programming languages. Tonight I want to blog about something a bit more complicated and more specific to R, but which can lead to massive speed-ups: interfacing C/C++ within R codes.

The rationale behind is that R is an amazing programming language for statisticians, with great packages available to do pretty much everything, from data analysis to beautiful graphs… but it runs definitely slower than low-level or middle-level languages like C or  C++. No worries, it’s pretty easy to insert C++ snippets inside R programs, using packages like inline and Rcpp. For those of you who already use python, it’s very similar to scipy.weave. Here’s an example:

library(inline)
doublematrix <- cxxfunction(signature(x = "numeric"), body = '
Rcpp::NumericMatrix xcpp(x);
int nrows = xcpp.nrow();
int ncolumns = xcpp.ncol();
for (int i = 0; i < nrows; i++){
    for (int j = 0; j < ncolumns; j++){
        xcpp[nrows * j + i] *= 2;
    }
}
return xcpp;
', plugin="Rcpp")
print(doublematrix(matrix(1:10, nrow = 2)))

Created by Pretty R at inside-R.org

This code defines a function “doublematrix” that takes a matrix x as an argument, and doubles all of its elements. As you can see the C code is inside a string called “body”. Hence, you don’t even have to handle separate files, the package takes care of all the boring stuff! To run this example on your machine, you just have to install inline and Rcpp, which are both on CRAN.

Note that the Rcpp “plugin” allows to use convenient types within the C code (“Rcpp::NumericMatrix” for instance), the type conversion is done implicitly, you don’t have to deal with the garbage collector… it’s already good enough for me! And much more advanced functionalities are supported (C++ templates, types equivalent to R data frames and many other types, though I didn’t find the simple equivalent of “array”, easy links with STL and GSL functions…). Have a look at the Rcpp webpage if you want to know more, especially the FAQ!

Note that the adaptive MCMC package developed by Jeff Rosenthal provides a good start to look into more advanced interfacing techniques, where pre-compiled C functions are loaded dynamically within R.

6 Responses

Subscribe to comments with RSS.

  1. Julyan Arbel said, on 4 February 2011 at 12:38

    Cool, so easy! inline and Rcpp are well installed, still I have the following error:
    Erreur dans compileCode(f, code, language = language, verbose = verbose) :
    Compilation ERROR, function(s)/method(s) not created!
    Any idea why?

  2. Pierre Jacob said, on 4 February 2011 at 13:07

    As stated by the FAQ
    http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-FAQ.pdf
    the Rcpp library works on windows but not with Visual Studio. So you need to be able to use another C++ compiler, I’m guessing mingw (the windows version of GCC) should be fine: http://www.mingw.org/

  3. Hubs « IREvalEtAl said, on 8 February 2011 at 08:14

    […] Today I learnt, R has support for inline C++. […]

  4. QuantTrader said, on 23 April 2011 at 22:44

    Hi,
    very nice post! I am trying to optimize my code these days so I will definitely implement and test your suggestions. Thanks.

  5. Helmingstay said, on 28 August 2012 at 10:54

    Did you ever figure out the STL links? That, GSL, and the very nice Armadillo linear algebra library are all pretty easy.

    With an Rcpp package, it’s easy to use R objects to instantiate C++ classes. You can even build std::vectors of those claseses ala std::vector(classinstantiation_obj)…

    • Helmingstay said, on 28 August 2012 at 10:55

      whoops, there were angle-brackets that got filtered out there, incidentally:
      vector\(instobj)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: