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
gslrng. This variable contains a short C++ code
segment, which is then transformed by the function
into a function of two arguments assigned to
## 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
cfunctiondefines two variables
n— which the C++ function then reads in from R and converts to two integers
seedis used to initialize the random-number generator, and
lendraws are then taken and stored in the STL vector
vwhich 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
cfunctionto add the GSL include line, specify that we want to compile and link against Rcpp and provide
-Larguments to compile and link with the GSL. (The include statement is not needed as the compiler would have found them in
/usr/includeanyway, 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++.