Rcpp and inline example

December 20, 2009

(This article was first published on Thinking inside the box , and kindly contributed to R-bloggers)

Following up on yesterday’s
Rcpp 0.7.0
, 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;
       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);

       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"),
                      includes="#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
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 their blog: Thinking inside the box .

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, 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.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)