Using R — Callling C code with Rcpp

This entry is part 11 of 20 in the series Using R

In two previous posts we described how R can call C code with .C() and the more complex yet more robust option of calling C code with .Call().  Here we will describe how the Rcpp package can be used to greatly simplify your C code without forcing you to become expert in C++.

First off, kudos to Dirk Eddelbuettel and Romain François who’s tireless efforts to improve, promote and document Rcpp have produced one of CRAN’s most popular packages.  As of Rcpp version 0.9.15 there are 82 “Reverse depends” — other packages that utilize Rcpp.  There are also eight vignettes that describe the package in human terms.  Even more accessible are Dirk’s papers and presentations and Romain’s blog.  While we’re heaping praise, let’s not forget to mention Romain’s graph gallery.

Even after all that praise and all the available documentation we’re still left with the problem of where to start.  There are no vignettes targeted at the R user who wants to try out a couple of C routines but isn’t otherwise inclined to learn C++ and who doesn’t want to write an entire package — at least not yet.  A good place to review the motivation behind Rcpp and see some great example code would be Dirk’s 62 slide  Rcpp: Seamless R and C++ Integration presentation or the longer, 146 slide Rcpp Tutorial Parts I and II.  Between those two presentations and the package documentation you really have access to all the information you need.  However, in the interest of continuing our “baby steps” theme, we will once again recreate our three “Hello World!” examples, this time using Rcpp.

Getting Set Up

The very first thing you will have to do is install the Rcpp package.  (See Installing Packages if this is unfamiliar.)  If you keep your version of R at the bleeding edge, you can do this by invoking R and telling it to just grab the latest package.

Oops!  Some of us are slightly behind the times.  Rather than upgrade my version of R today, I’ll instead take a look inside the Rcpp Old sources: archive and find a version that was released close to the (2011-12-22) date of my version of R.  Version 0.9.10 was released on 17-Feb-2012 and should be compatible.  We’ll install that version from the command line with the following:

The last thing we need to do is let our compilers and linkers know where the new, Rcpp libraries are located (see slide 48 of the Tutorial).

Yes, Whew! once again.  But now we are ready to write C code that looks more like C code and, once we embrace Rcpp’s syntactic sugar, perhaps even like R code.

Baby steps example

When using the Rcpp package we are still using the .Call() interface to C code.  All of the changes will be seen in the C code which now becomes C++ code with a .cpp extension.  Because C++ is a superset of C, this is perfectly legal but we will need to educate Rcpp by using RcppExport.  According to slide 136 of the Tutorial:

OK.  Here we go with our first  C++ example: helloA2.cpp.

It looks remarkably similar to helloA1.c from the previous post and is compiled and invoked in much the same way.

The R wrapper code is identical to the one in the previous post for helloA1.c as is the usage in an R session.

Simpler C code

We’ll leave out the wrappers and R session in the next two examples as they are identical to the examples in the previous post.  But just look at how much simpler the C code gets!  Instead of allocating memory, protecting from garbage collection and all that casting between types we get this for helloB2.cpp:

and this for helloC2.cpp:

Now we’re talkin’.  This is starting to look like code a C programmer, Heck, even a Java programmer could get comfortable with.  The tools provided by Rcpp are systematic, readable and, as a welcome change, very well documented.  Whereas I was hesitant to recommend writing C code for the .Call() interface because of the painful learning curve, I am happy to report that the learning curve for using Rcpp does not require that you first climb a mountain to learn C++.  C programmers of all skill levels will benefit from using Rcpp.

More Examples

While a “Hello World!” example may be a great place to start, it is unlikely to provide any useful template code for people.  For that you will want to poke around in the source code of the many packages that depend on Rcpp.  Dirk Eddelbuettel is of course quite interested in these dependent packages and describes some of them on slide 42 of Seamless R and C++ Integration and slide 29 of Rcpp Tutorial Parts I and II.  I was pleased to learn that some of these packages are written in C and will hopefully provide excellent example code.

Hadley Wickham has written a comprehensive tutorial for the Rcpp package.

To everyone who is trying to improve and extend R — Best of Luck!

Series NavigationUsing R — .Call(“hello”)Using R — Packaging a C library in 15 minutes
This entry was posted in R and tagged , , . Bookmark the permalink.

3 Responses to Using R — Callling C code with Rcpp

  1. JJ Allaire says:

    Hi Jonathan,

    Great write-ups on using C/C++ with R! In Rcpp version 0.10.0 (released today) we added a new much cleaner syntax for exporting C++ functions to R. It’s called “Rcpp attributes” and it basically allows you to write functions in a cpp file and then just source them into R using the sourceCpp() function. It’s also possible to use cppFunction() and evalCpp() to embed C++ code inside an R script.

    All the details are in this vignette (and Rd files within the package): Rcpp attributes [PDF].


  2. Honglang Wang says:

    there is a problem:
    $ export PKG_CPPFLAGS=Rscript -e "Rcpp:::CxxFlags()"
    $ export PKG_CPPFLAGS=Rscript -e "Rcpp:::LdFlags()"
    should be
    $ export PKG_CPPFLAGS=Rscript -e 'Rcpp:::CxxFlags()'
    $ export PKG_CPPFLAGS=Rscript -e 'Rcpp:::LdFlags()'
    i.e. the “…” should be chaged to be ‘…’

    • Jonathan Callahan says:

      I haven’t had any problem with the double quotes. But Cutting and pasting can sometimes turn the surrounding backticks “`” into apostrophes “‘” which won’t work. The invokation of R script needs to be surrounded by backticks.