Hadley Wickham has written a comprehensive tutorial for the Rcpp package, which makes it easy to create C++ code embedded in R programs. Hadley explains why you might want to do this in the introduction:
Sometimes R code just isn't fast enough - you've used profiling to find the bottleneck, but there's simply no way to make the code any faster. This chapter is the answer to that problem. You'll learn how to rewrite key functions in C++ to get much better performance, while not taking too much longer to write. The key to this magic is Rcpp, a fantastic tool written by Dirk Eddelbuettel and Romain Francois (with key contribution by Doug Bates, John Chambers and JJ Allaire), that makes it dead simple to connect C++ to R. It is possible to write high performance code in C or Fortran. This might produce faster code than C++ (but probably not), but it will take you much much longer to write. Without Rcpp, you must sacrifice many helpful wrappers and master the complex C internals of R yourself. Rcpp is currently the best balance between speed and convenience, and any other approach will be much more painful.
No knowledge of C++ is required, so if you have some R code — especially tight loops — that you need to speed up, you should definitely check it out the whole tutorial.
This guide comes from a book on writing reproducible code that Hadley's working on. You can browse the other sections of the book on GitHub — even though the book isn't yet complete there's a wealth of useful information there for any serious R programmer.
Hadley Wickham (github): Rcpp
Thanks for the heads up. Hadley's devtools tutorial was great as well.
Posted by: isomorphismes | November 28, 2012 at 20:32
I will love this recent influx of rcpp stuff and i will certainly use it to get started. I have one question though: What are the situations in which I can expect the most benefits from a c++ implementations?
Posted by: greg | November 30, 2012 at 10:31
couldn't get Rcpp's cppFunction to work. I downloaded the latest Revolution R on Windows 7 (Community 6.0, R version 2.14.2 (2012-02-29)), and I get
> library(Rcpp)
>
> cppFunction('
+ + NumericVector myRcpptest () {
+ + NumericVector out(3);
+ + for(int i = 0; i < 3; ++i) {
+ + out[i] = 0.0 + i;
+ + }
+ + return out;
+ + }
+ + ')
Error: could not find function "cppFunction"
Works OK on open-source R. Tried 32- and 64-bit versions of Revolution R. I'm wondering if I need dev tools or need to tell it where to find the compiler.
Would like to write a critical section in C++ and then also use doParallel to leverage multiple cores.
Posted by: druce | February 23, 2013 at 18:27
@druce
Are you sure you have the most recent Rcpp installed? devtools isn't required -- that's purely an R message.
Posted by: helmingstay | March 22, 2013 at 16:08
@greg
Thank you, your code helped me.
Posted by: Ismail | May 14, 2013 at 02:37