Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 v(len);

r = gsl_rng_alloc (gsl_rng_default);

gsl_rng_set (r, (unsigned long) seed);
for (int i=0; i

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.)

function with arguments zero for the seed and five for the length, and print
the results vector returned to R from C++.

var vglnk = {key: '949efb41171ac6ec1bf7f206d57e90b8'};
(function(d, t) {
var s = d.createElement(t);
s.type = 'text/javascript';
s.async = true;
// s.defer = true;
var r = d.getElementsByTagName(t)[0];
r.parentNode.insertBefore(s, r);
}(document, 'script'));

Related
ShareTweet