Rcpp and inline example

December 20, 2009
By

(This article was first published on dirk.eddelbuettel, and kindly contributed to R-bloggers)

Following up on yesterday's Rcpp 0.7.0 release, here is a quick example of why the new feastures can be so useful.

The following R code defines a character variable gslrng. This variable contains a short C++ code segment, which is then transformed by the function cfunction into a function of two arguments assigned to funx:

 ## now use Rcpp to pass down a parameter for the seed, and a vector size gslrng <- ' int seed = RcppSexp(s).asInt(); int len = RcppSexp(n).asInt(); gsl_rng *r; gsl_rng_env_setup(); std::vector<double> v(len); r = gsl_rng_alloc (gsl_rng_default); gsl_rng_set (r, (unsigned long) seed); for (int i=0; i<len; i++) { v[i] = gsl_rng_get (r); } gsl_rng_free(r); return RcppSexp(v).asSexp();
 ' ## turn into a function that R can call ## compileargs redundant on Debian/Ubuntu as gsl headers are found anyway funx <- cfunction(signature(s="numeric", n="numeric"), gslrng, includes="#include <gsl/gsl_rng.h>", Rcpp=TRUE, cppargs="-I/usr/include", libargs="-lgsl -lgslcblas") print(funx(0, 5)) 

The signature argument to cfunction defines two variables s and n -- which the C++ function then reads in from R and converts to two integers seed and len. seed is used to initialize the random-number generator, and len draws are then taken and stored in the STL vector v which returned at the end.

As the R level, we now have a function of two arguments returning a vector of RNG draws of the given lenth and using the given seed.

Also note how we tell cfunction to add the GSL include line, specify that we want to compile and link against Rcpp and provide -I and -L arguments to compile and link with the GSL. (The include statement is not needed as the compiler would have found them in /usr/include anyway, but it shows how to set this if needed.)

Finally, we simply call our freshly compiled, linked and loaded C++ function with arguments zero for the seed and five for the length, and print the results vector returned to R from C++.

To leave a comment for the author, please follow the link and comment on his blog: dirk.eddelbuettel.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.