RcppGSL: Easier GSL use from R via Rcpp
Dirk Eddelbuettel

Romain François

Version 0.3.0 as of August 30, 2015

Abstract
The GNU Scientific Library, or GSL, is a collection of numerical routines for scientific computing (Galassi
et al., 2010). It is particularly useful for C and C++ programs as it provides a standard C interface to awide range of mathematical routines such as special functions, permutations, combinations, fast fouriertransforms, eigensystems, random numbers, quadrature, random distributions, quasi-random sequences,
Monte Carlo integration, N-tuples, differential equations, simulated annealing, numerical differentiation,interpolation, series acceleration, Chebyshev approximations, root-finding, discrete Hankel transforms
physical constants, basis splines and wavelets. There are over 1000 functions in total with an extensive
test suite.
The RcppGSL package provides an easy-to-use interface between GSL and R, with a particular focus on
matrix and vector data structures. RcppGSL relies on Rcpp (Eddelbuettel and François, 2011; Eddelbuettel,
2013; Eddelbuettel, François, Allaire, Ushey, Kou, Chambers, and Bates, 2015) which is itself a packagethat eases the interfaces between R and C++.

1

Introduction

The GNU Scientific Library, or GSL, is a collection of numerical routines for scientific computing (Galassi
et al., 2010). It is a rigourously developed and tested library providing support for a wide range of scientificor numerical tasks. Among the topics covered in the GSL are complex numbers, roots of polynomials,
special functions, vector and matrix data structures, permutations, combinations, sorting, BLAS support,
linear algebra, fast fourier transforms, eigensystems, random numbers, quadrature, random distributions,
quasi-random sequences, Monte Carlo integration, N-tuples, differential equations, simulated annealing,
numerical differentiation, interpolation, series acceleration, Chebyshev approximations, root-finding,
discrete Hankel transforms least-squares fitting, minimization, physical constants, basis splines andwavelets.
Support for C programming with the GSL is available as the GSL itself is written in C, and provides
a C-language Application Programming Interface (API). Access from C++ is possible, albeit not at an
abstraction level that could be offered by dedicated C++ implementations. Several C++ wrappers for the
GSL have been written over the years; none reached a state of completion comparable to the GSL itself.
The GSL combines broad coverage of scientific topics, serious implementation effort, and the use of
the well-known GNU General Public License (GPL). This has lead to fairly wide usage of the library. As aconcrete example, we can consider the Comprehensive R Archive Network (CRAN) repository network for
the R language and environment (R Development Core Team, 2015). CRAN contains over three dozen
packages interfacing the GSL. Of these more than half interface the vector or matrix classes as shown in
Table 1. This provides empirical evidence indicating that the GSL is popular among programmers using
either the C or C++ language for solving problems applied science.
At the same time, the Rcpp package (Eddelbuettel and François, 2011; Eddelbuettel, 2013; Eddelbuettel
et al., 2015) offers a higher-level interface between R and C++. Rcpp permits R objects like vectors,
matrices, lists, functions, environments, . . ., to be manipulated directly at the C++ level, and alleviates theneeds for complicated and error-prone parameter passing and memory allocation. It also allows compact
vectorised expressions similar to what can be written in R directly at the C++ level.

1Packageabn
BayesLogit
BayesSAE
BayesVarSel
BH
bnpmr
BNSP
cghsegcit
diversitreeeco
geoCount
graphscan
gsl
gstat
hgm
HiCsegigraphKFKSDS
libamtrack
mixcatmvabundoutbreaker
R2GUESS
RCA
RcppGSLRcppSMC
RcppZiggurat
RDieHarderridge
Rlibeemd
Runuran
SemiCompRisks
simplexreg
stsm
survSNP
TKF
topicmodels
VBLPCM
VBmix

Any gsl header

gsl_vector.h

gsl_matrix.h

?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?

?

?

?
?
?

?
?

?
?

?
?
?

?
?
?

?

?
?
?
?

?
?
?
?

?

?

?
?
?

?
?

?
?
?
?
?
?

?
?
?
?
?
?

Table 1: CRAN Package Usage of GSL outright, for vectors and for matrices.
Note: Data gathered in late July 2015 by use of grep searching (recursively) for inclusion of any GSL header, or the vector andmatrix headers specifically, within the src/ or inst/include/ directories of expanded source code archives of the CRAN network.
Convenient (temporary) shell access to such an expanded code archive via WU Vienna is gratefully acknowledged.

2

The RcppGSL package discussed here aims to close the gap. It offers access to GSL functions, inparticular via the vector and matrix data structures used throughout the GSL, while staying closer to the‘whole object model’ familar to the R programmer.
The rest of paper is organised as follows. The next section shows a motivating example of a fast linear
model fit routine using GSL functions. The following section discusses support for GSL vector types, which
is followed by a section on matrices. The following two section discusses error handling, and then use of
RcppGSL in your own package. This is followed by short discussions of how to use RcppGSL with inline
and Rcpp Attributes, respectively, before a short concluding summary.

2

Motivation: fastLm

Fitting linear models is a key building block of analysing and modeling data. R has a very complete
and feature-rich function in lm() which provides a model fit as well as a number of diagnostic measure,either directly or via the summary() method for linear model fits. The lm.fit() function provides afaster alternative (which is however recommend only for for advanced users) which provides estimates
only and fewer statistics for inference. This may lead to user requests for a routine which is both fast
and featureful enough. The fastLm routine shown here provides such an implementation as part of the
RcppGSL package. It uses the GSL for the least-squares fitting functions and provides a nice example for
GSL integration with R.

#include <RcppGSL.h>#include <gsl/gsl_multifit.h>#include <cmath>// declare a dependency on the RcppGSL package; also activates plugin// (but not needed when ’LinkingTo: RcppGSL’ is used with a package)//// [[Rcpp::depends(RcppGSL)]]// tell Rcpp to turn this into a callable function called ’fastLm’//// [[Rcpp::export]]
Rcpp::List fastLm(const RcppGSL::Matrix & X, const RcppGSL::Vector & y) {// row and column dimension// assigned but not returned// to hold the coefficient vector// and the covariance matrix

int n = X.nrow(), k = X.ncol();double chisq;
RcppGSL::Vector coef(k);RcppGSL::Matrix cov(k,k);// the actual fit requires working memory which we allocate and then free
gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc (n, k);
gsl_multifit_linear (X, y, coef, cov, &chisq, work);
gsl_multifit_linear_free (work);// assign diagonal to a vector, then take square roots to get std.error
Rcpp::NumericVector std_err;
std_err = gsl_matrix_diagonal(cov);// need two step decl. and assignment
std_err = Rcpp::sqrt(std_err);// sqrt() is an Rcpp sugar function
return Rcpp::List::create(Rcpp::Named("coefficients") = coef,
Rcpp::Named("stderr")= std_err,
Rcpp::Named("df.residual") = n - k);}

3

The function interface defines two RcppGSL variables: a matrix and a vector. Both use the standard
numeric type double as discussed below. The GSL supports other types ranging from lower precision
floating point to signed and unsigned integers as well as complex numbers. The vector and matrix classes
are templated for use with all these C / C++ types—though R uses only double and int. For these latter
two, we offer a shorthand definition via a typedef which allows a shorter non-template use. Having
extracted the row and column dimentions, we then reserve another vector and matrix to hold the resulting
coefficient estimates as well as the estimate of the covariance matrix. Next, we allocate workspace using a
GSL routine, fit the linear model and free the just-allocated workspace. The next step involves extracting
the diagonal element from the covariance matrix, and taking the square root (using a vectorised function
from Rcpp). Finally we create a named list with the return values.
In earlier version of the RcppGSL package, we also explicitly called free() to return temporary
memory allocation to the operating system. This step had to be done as the underlying objects aremanaged as C objects. They conform to the GSL interface, and work without any automatic memory
management. But as we provide a C++ data structure for matrix and vector objects, we can manage
them using C++ facilities. In particular, the destructor can free the memory when the object goes out of
scope. Explicit free() calls are still permitted as we keep track the object status so that memory cannot
accidentally be released more than once. Another more recent addition permits use of const & in theinterface. This instructs the compiler that values of the corresponding variable will not be altered, and arepassed into the function by reference rather than by value.
We note that RcppArmadillo (François, Eddelbuettel, and Bates, 2015; Eddelbuettel and Sanderson,2014) implements a matching fastLm function using the Armadillo library by Sanderson (2010), and can
do so with even more compact code due to C++ features. Moreover, RcppEigen (Bates, François, and Eddelbuettel, 2015; Bates and Eddelbuettel, 2013) provides a fastLm implementation with a comprehensive
comparison of matrix decomposition methods.

3

Vectors

This section details the different vector represenations, starting with their definition inside the GSL. We
then discuss our layering before showing how the two types map. A discussion of read-only ‘vector view’classes concludes the section.

3.1

GSL Vectors

GSL defines various vector types to manipulate one-dimensionnal data, similar to R arrays. For example
the gsl_vector and gsl_vector_int structs are defined as:
typedef struct{size_t size;
size_t stride;
double * data;
gsl_block * block;int owner;} gsl_vector;
typedef struct {size_t size;
size_t stride;int * data;
gsl_block_int * block;int owner;} gsl_vector_int;
A typical use of the gsl_vector struct is given below:

4int i;gsl_vector *v = gsl_vector_alloc(3);// allocate a gsl_vector of size 3

for (i = 0; i < 3; i++) {gsl_vector_set(v, i, 1.23 + i);}// fill the vector

double sum = 0.0;
for (i = 0; i < 3; i++) {sum += gsl_vector_set(v, i);}// access elements

gsl_vector_free(v);// free the memory

Note that we have to explicitly free the allocated memory at the end. With C-style programming, thisstep is always the responsibility of the programmer.

3.2

RcppGSL::vector

RcppGSL defines the template RcppGSL::vector<T> to manipulate gsl_vector pointers taking advantage of C++ templates. Using this template type, the previous example now becomes:

int i;
RcppGSL::vector<double> v(3);// allocate a gsl_vector of size 3

for (i = 0; i < 3; i++) {v[i] = 1.23 + i;}// fill the vector

double sum = 0.0;
for (i = 0; i < 3; i++) {sum += v[i];}// access elements

v.free();// (optionally) free the memory// also automatic when out of scope

The class RcppGSL::vector<double> is a smart pointer which can be deployed anywhere wherea raw pointer gsl_vector can be used, such as the gsl_vector_set and gsl_vector_get functions
above.
Beyond the convenience of a nicer syntax for allocation (and of course the managed release ofmemory either via free() or when going out of scope), the RcppGSL::vector template faciliates interchange of GSL vectors with Rcpp objects, and hence R objects. The following example defines a.Call compatible function called sum_gsl_vector_int that operates on a gsl_vector_int throughthe RcppGSL::vector<int> template specialization:// [[Rcpp::export]]
int sum_gsl_vector_int(const RcppGSL::vector<int> & vec){int res = std::accumulate(vec.begin(), vec.end(), 0);
return res;}
Here we no longer need to call free() explicitly as the vec allocation is returned automatically at theend of the function body when the variable goes out of scope.
Once the function has created via sourceCpp() or cppFunction() from Rcpp Attributes (see section 8
for more on this), it can then be called from R :5

> sum_gsl_vector_int(1:10)[1] 55
A second example shows a simple function that grabs elements of an R list as gsl_vector objects
using implicit conversion mechanisms of Rcpp// [[Rcpp::export]]
double gsl_vector_sum_2(const Rcpp::List & data) {// grab "x" as a gsl_vector through the RcppGSL::vector<double> classconst RcppGSL::vector<double> x = data["x"];// grab "y" as a gsl_vector through the RcppGSL::vector<int> classconst RcppGSL::vector<int> y = data["y"];double res = 0.0;
for (size_t i=0; i< x->size; i++) {res += x[i] * y[i];}return res;// return the result, memory freed automatically}called from R:> data <- list( x = seq(0,1,length=10), y = 1:10 )> gsl_vector_sum_2(data)[1] 36.66667

3.3

Mapping

Table 2 shows the mapping between types defined by the GSL and their corresponding types in the
RcppGSL package.
GSL vector

RcppGSL

gsl_vector
gsl_vector_int
gsl_vector_float
gsl_vector_long
gsl_vector_char
gsl_vector_complex
gsl_vector_complex_float
gsl_vector_complex_long_double
gsl_vector_long_double
gsl_vector_short
gsl_vector_uchar
gsl_vector_uint
gsl_vector_ushort
gsl_vector_ulong

RcppGSL::vector<double> as well as RcppGSL::Vector
RcppGSL::vector<int> as well as RcppGSL::IntVector
RcppGSL::vector<float>
RcppGSL::vector<long>
RcppGSL::vector<char>
RcppGSL::vector<gsl_complex>
RcppGSL::vector<gsl_complex_float>
RcppGSL::vector<gsl_complex_long_double>
RcppGSL::vector<long double>
RcppGSL::vector<short>
RcppGSL::vector<unsigned char>
RcppGSL::vector<unsigned int>
RcppGSL::vector<insigned short>
RcppGSL::vector<unsigned long>

Table 2: Correspondance between GSL vector types and templates defined in RcppGSL.
As shown, we also define two convenient shortcuts for the very common case of double and int vectors. First, RcppGSL::Vector is a short-hand for the RcppGSL::vector<double> template instantiation.
Second, RcppGSL::IntVector does the same for integer-valued vectors. Other types still require explicit
templates.

6

3.4

Vector Views

Several GSL algorithms return GSL vector views as their result type. RcppGSL defines the template class
RcppGSL::vector_view to handle vector views using C++ syntax.
// [[Rcpp::export]]
Rcpp::List test_gsl_vector_view() {int n = 10;
RcppGSL::vector<double> v(n);for (int i=0 ; i<n; i++) {v[i] = i;}const RcppGSL::vector_view<double> v_even =gsl_vector_subvector_with_stride(v,0,2,n/2);
const RcppGSL::vector_view<double> v_odd =gsl_vector_subvector_with_stride(v,1,2,n/2);
return Rcpp::List::create(Rcpp::Named("even") = v_even,
Rcpp::Named("odd" ) = v_odd);}
As with vectors, C++ objects of type RcppGSL::vector_view can be converted implicitly to theirassociated GSL view type. Table 3 displays the pairwise correspondance so that the C++ objects can bepassed to compatible GSL algorithms.
gsl vector views

RcppGSL

gsl_vector_view
gsl_vector_view_int
gsl_vector_view_float
gsl_vector_view_long
gsl_vector_view_char
gsl_vector_view_complex
gsl_vector_view_complex_float
gsl_vector_view_complex_long_double
gsl_vector_view_long_double
gsl_vector_view_short
gsl_vector_view_uchar
gsl_vector_view_uint
gsl_vector_view_ushort
gsl_vector_view_ulong

RcppGSL::vector_view<double>; RcppGSL::VectorView
RcppGSL::vector_view<int>; RcppGSL::IntVectorView
RcppGSL::vector_view<float>
RcppGSL::vector_view<long>
RcppGSL::vector_view<char>
RcppGSL::vector_view<gsl_complex>
RcppGSL::vector_view<gsl_complex_float>
RcppGSL::vector_view<gsl_complex_long_double>
RcppGSL::vector_view<long double>
RcppGSL::vector_view<short>
RcppGSL::vector_view<unsigned char>
RcppGSL::vector_view<unsigned int>
RcppGSL::vector_view<insigned short>
RcppGSL::vector_view<unsigned long>

Table 3: Correspondance between GSL vector view types and templates defined in RcppGSL.
The vector view class also contains a conversion operator to automatically transform the data of theview object to a GSL vector object. This enables use of vector views where GSL would expect a vector.
And as before, double and int types can be accessed via the typedef variants RcppGSL::VectorView
and RcppGSL::IntVectorView, respectively.
Lastly, in order to support const & behaviour, all gsl_vector_XXX_const_view variants are also
supported (where XXX stands for any of the atomistic C and C++ data types).

4

Matrices

The GSL also defines a set of matrix data types : gsl_matrix, gsl_matrix_int etc ... for which RcppGSL
defines a corresponding convenience C++ wrapper generated by the RcppGSL::matrix template.

7

4.1

Creating matrices

The RcppGSL::matrix template exposes three constructors.
// convert an R matrix to a GSL matrix
matrix(SEXP x) throw(::Rcpp::not_compatible)// encapsulate a GSL matrix pointermatrix(gsl_matrix* x)// create a new matrix with the given number of rows and columns
matrix(int nrow, int ncol)

4.2

Implicit conversion

RcppGSL::matrix defines an implicit conversion to a pointer to the associated GSL matrix type, as well
as dereferencing operators. This makes the class RcppGSL::matrix look and feel like a pointer to a GSL
matrix type.
gsltype* data;
operator gsltype*() { return data; }gsltype* operator->() const { return data; }gsltype& operator*() const { return *data; }4.3

Indexing

Indexing of GSL matrices is usually the task of the functions gsl_matrix_get, gsl_matrix_int_get, ...
and gsl_matrix_set, gsl_matrix_int_set, ...
RcppGSL takes advantage of both operator overloading and templates to make indexing a GSL matrix
much more convenient.

RcppGSL::matrix<int> mat(10,10);// create a matrix of size 10x10

for (int i=0; i<10: i++) {mat(i,i) = i;}// fill the diagonal// no need for setter function

4.4

Methods

The RcppGSL::matrix type also defines the following member functions:

nrow extracts the number of rows
ncol extract the number of columns
size extracts the number of elements
free releases the memory (also called via destructor)

4.5

Matrix views

Similar to the vector views discussed above, the RcppGSL also provides an implicit conversion operator
which returns the underlying matrix stored in the matrix view class.

8

5

Error handler

When input values for GSL functions are invalid, the default error handler will abort the program after
printing an error message. This leads R to an abortion error. To avoid this behaviour, one needs to avoid it
first by using gsl_set_error_handler_off(), and then detect error conditions by checking whether
the result is NAN or not.
// close the GSL error handler
gsl_set_error_handler_off();// call GSL function with some invalid values
double res = gsl_sf_hyperg_2F1(1, 1, 1.1467003, 1);// detect the result is NAN or not
if (ISNAN(res)) {Rcpp::Rcout << "Invalid input found!" << std::endl;}
See http://thread.gmane.org/gmane.comp.lang.r.rcpp/7905 for a longer discussion of the related issues.
Starting with release 0.2.4, two new functions are available: gslSetErrorHandlerOff() and gslResetErrorHandler() which allow to turn off the error handler (as discussed above), and to reset to theprior (default) value. In addition, the package now also calls gslSetErrorHandlerOff() when being
attached, ensuring that the GSL error handler is turned off by default.

6

Using RcppGSL in your package

The RcppGSL package contains a complete example package providing a single function colNorm which
computes a norm for each column of a supplied matrix. This example adapts a matrix example fromthe GSL manual that has been chosen primarily as a means to showing how to set up a package to use
RcppGSL.
Needless to say, we could compute such a matrix norm easily in R using existing facilities. One suchpossibility is a simple apply(M, 2, function(x) sqrt(sum(x^2))) as shown on the corresponding
help page in the example package inside RcppGSL. One point in favour of using the GSL code is thatit employs a BLAS function so on sufficiently large matrices, and with suitable BLAS libraries installed,
this variant could be faster due to the optimised code in high-performance BLAS libraries and/or theinherent parallelism a multi-core BLAS variant which compute compute the vector norm in parallel. On
all ‘reasonable’ matrix sizes, however, the performance difference should be neglible.

6.1

The configure script

6.1.1

Using autoconf

Using RcppGSL means employing both the GSL and R. We may need to find the location of the GSL
headers and library, and this done easily from a configure source script which autoconf generates froma configure.in source file such as the following:9

AC_INIT([RcppGSLExample], 0.1.0)## Use gsl-config to find arguments for compiler and linker flags#### Check for non-standard programs: gsl-config(1)AC_PATH_PROG([GSL_CONFIG], [gsl-config])## If gsl-config was found, let’s use it
if test "${GSL_CONFIG}" != ""; then# Use gsl-config for header and linker arguments (without BLAS which we get from R)
GSL_CFLAGS=‘${GSL_CONFIG} --cflags‘
GSL_LIBS=‘${GSL_CONFIG} --libs-without-cblas‘
else
AC_MSG_ERROR([gsl-config not found, is GSL installed?])fi# Now substitute these variables in src/Makevars.in to create src/Makevars
AC_SUBST(GSL_CFLAGS)
AC_SUBST(GSL_LIBS)

AC_OUTPUT(src/Makevars)
A source file such as this configure.in gets converted into a script configure by invoking the
autoconf program.
We note that many other libraries use a similar (but somewhat newer and by-now fairly standard)
scripting frontend called pkg-config which be deployed in a very similar by other packages. Calls suchas the following two can be used from configure in a very similar manner:

pkg-config --cflags libpng
pkg-config --libs libpng
where libpng (for the png image format) is used just for illustration.

6.1.2

Using functions provided by RcppGSL

RcppGSL provides R functions (in the file R/inline.R) that allow us to retrieve the same information.
Therefore the configure script can also be written as:#!/bin/sh

GSL_CFLAGS=‘${R_HOME}/bin/Rscript -e "RcppGSL:::CFlags()"‘
GSL_LIBS=‘${R_HOME}/bin/Rscript -e "RcppGSL:::LdFlags()"‘sed -e "s|@GSL_LIBS@|${GSL_LIBS}|" \-e "s|@GSL_CFLAGS@|${GSL_CFLAGS}|" \src/Makevars.in > src/Makevars
Similarly, the configure.win for windows can be written as:

GSL_CFLAGS=‘${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe -e "RcppGSL:::CFlags()"‘
GSL_LIBS=‘${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe -e "RcppGSL:::LdFlags()"‘sed -e "s|@GSL_LIBS@|${GSL_LIBS}|" \-e "s|@GSL_CFLAGS@|${GSL_CFLAGS}|" \src/Makevars.in > src/Makevars.win
This allows for a simpler and more direct way to just set the compile and link options, taking advantage

10

of the installed RcppGSL package. See the RcppZiggurat package for an example.

6.2

The src directory

The C++ source file takes the matrix supplied from R and applies the GSL function to each column.

#include <RcppGSL.h>#include <gsl/gsl_matrix.h>#include <gsl/gsl_blas.h>// [[Rcpp::export]]
Rcpp::NumericVector colNorm(const RcppGSL::Matrix & G) {int k = G.ncol();
Rcpp::NumericVector n(k);// to store resultsfor (int j = 0; j < k; j++) {RcppGSL::vector_view<double> colview = gsl_matrix_const_column(G, j);n[j] = gsl_blas_dnrm2(colview);}
return n;// return vector}
The Makevars.in file governs the compilation and uses the values supplied by configure duringbuild-time:# set by configure
GSL_CFLAGS = @GSL_CFLAGS@GSL_LIBS= @GSL_LIBS@# combine with standard arguments for R
PKG_CPPFLAGS = $(GSL_CFLAGS)
PKG_LIBS = $(GSL_LIBS)
The variables surrounded by will be filled by configure during package build-time. As discussed
above, this can either rely on autoconf or a possibly-simpler Rscript.

6.3

The R directory

The R source is very simply: it contains a single file created by the Rcpp::compileAttributes() function
implementing the wrapper to the colNorm() function.

7

Using RcppGSL with inline

The inline package (Sklyar, Murdoch, Smith, Eddelbuettel, and François, 2015) is very helpful for
prototyping code in C, C++ or Fortran as it takes care of code compilation, linking and dynamic loading
directly from R. It has been used extensively by Rcpp, for example in the numerous unit tests.
The example below shows how inline can be deployed with RcppGSL. We implement the same column
norm example, but this time as an R script which is compiled, linked and loaded on-the-fly. Compared tostandard use of inline, we have to make sure to add a short section declaring which header files from
GSL we need to use; the RcppGSL then communicates with inline to tell it about the location and namesof libraries used to build code against GSL.

11

> require(inline)> inctxt='#include <gsl/gsl_matrix.h>#include <gsl/gsl_blas.h>'> bodytxt='
RcppGSL::matrix<double> M = sM;
int k = M.ncol();
Rcpp::NumericVector n(k);// create data structures from SEXP// to store resultsfor (int j = 0; j < k; j++) {RcppGSL::vector_view<double> colview = gsl_matrix_column (M, j);n[j] = gsl_blas_dnrm2(colview);}
return n;// return vector'> foo <- cxxfunction(+
signature(sM="numeric"),+
body=bodytxt, inc=inctxt, plugin="RcppGSL")> M <- outer(sin(0:9), rep(1,10), "*") + outer(rep(1, 10), cos(0:9), "*")
> foo(M)[1] 4.314614 3.120504 2.193159 3.261141 2.534157 2.572810[7] 4.204689 3.652017 2.085236 3.073134
The RcppGSL inline plugin supports creation of a package skeleton based on the inline function.

> package.skeleton("mypackage", foo)

8

Using RcppGSL with Rcpp Attributes

Rcpp Attributes (Allaire, Eddelbuettel, and François, 2015) builds on the features of the inline package
described in previous section, and streamlines the compilation, loading and linking process even further.
It leverages the existing plugins for inline. We already showed the corresponding function in the previous
section. Here, we show it again as a self-contained example used via sourceCpp(). We stress that usage
is sourceCpp() is meant for interactive work at the R command-prompt, but is not the recommended
practice in a package.

12

#include <gsl/gsl_matrix.h>#include <gsl/gsl_blas.h>#include <RcppGSL.h>// declare a dependency on the RcppGSL package; also activates plugin//// [[Rcpp::depends(RcppGSL)]]// declare the function to be ’exported’ to R//// [[Rcpp::export]]
Rcpp::NumericVector colNorm(RcppGSL::Matrix M) {int k = M.ncol();
Rcpp::NumericVector n(k);// to store resultsfor (int j = 0; j < k; j++) {RcppGSL::VectorView colview = gsl_matrix_column (M, j);n[j] = gsl_blas_dnrm2(colview);}
return n;// return vector}/*** R## see Section 8.4.13 of the GSL manual:## create M as a sum of two outer products
M <- outer(sin(0:9), rep(1,10), "*") +outer(rep(1, 10), cos(0:9), "*")
colNorm(M)*/With the code above stored in a file, say, “gslNorm.cpp” one can simply call sourceCpp() to have thewrapper code added, and all of the compilation, linking and loading done — including the execution of
the short R segment at the end:

> sourceCpp("gslNorm.cpp")
The function cppFunction() is also available to convert a simple character string argument containing
a valid C++ function into a eponymous R function. And like sourceCpp(), it can also use plugins. See
the vignette “Rcpp-attributes” (Allaire et al., 2015) of the Rcpp package (Eddelbuettel et al., 2015) for
full details.

9

Summary

The GNU Scientific Library (GSL) by Galassi et al. (2010) offers a very comprehensive collection ofrigorously developed and tested functions for applied scientific computing under a widely-used andwell-understood Open Source license. This has lead to widespread deployment of GSL among a numberof disciplines.
Using the automatic wrapping and converters offered by the RcppGSL package presented here, R
users and programmers can now deploy algorithmns provided by the GSL with greater ease.

13

References
J. J. Allaire, Dirk Eddelbuettel, and Romain François. Rcpp Attributes, 2015. URL http://CRAN.
R-Project.org/package=Rcpp. Vignette included in R package Rcpp.
Douglas Bates and Dirk Eddelbuettel. Fast and elegant numerical linear algebra using the RcppEigen
package. Journal of Statistical Software, 52(5):1–24, 2013. URL http://www.jstatsoft.org/v52/
i05/.
Douglas Bates, Romain François, and Dirk Eddelbuettel. RcppEigen: Rcpp integration for the Eigen templated
linear algebra library, 2015. URL http://CRAN.R-Project.org/package=RcppEigen. R package
version 0.3.2.4.0.
Dirk Eddelbuettel. Seamless R and C++ Integration with Rcpp. Use R! Springer, New York, 2013. ISBN
978-1-4614-6867-7.
Dirk Eddelbuettel and Romain François. Rcpp: Seamless R and C++ integration. Journal of Statistical
Software, 40(8):1–18, 2011. URL http://www.jstatsoft.org/v40/i08/.
Dirk Eddelbuettel and Conrad Sanderson. RcppArmadillo: Accelerating R with high-performance C++
linear algebra. Computational Statistics and Data Analysis, 71:1054–1063, March 2014. doi: 10.1016/j.
csda.2013.02.005. URL http://dx.doi.org/10.1016/j.csda.2013.02.005.
Dirk Eddelbuettel, Romain François, JJ Allaire, Kevin Ushey, Qiang Kou, John Chambers, and Douglas Bates.
Rcpp: Seamless R and C++ Integration, 2015. URL http://CRAN.R-Project.org/package=Rcpp. R
package version 0.12.0.
Romain François, Dirk Eddelbuettel, and Douglas Bates. RcppArmadillo: Rcpp integration for Armadillotemplated linear algebra library, 2015. URL http://CRAN.R-Project.org/package=RcppArmadillo.
R package version 0.5.200.1.0.
Mark Galassi, Jim Davies, James Theiler, Brian Gough, Gerard Jungman, Patrick Alken, Michael Booth,and Fabrice Rossi. GNU Scientific Library Reference Manual, 3rd edition, 2010. URL http://www.gnu.
org/software/gsl. Version 1.14. ISBN 0954612078.
R Development Core Team. R: A Language and Environment for Statistical Computing. R Foundation for
Statistical Computing, Vienna, Austria, 2015. URL http://www.R-project.org/.
Conrad Sanderson. Armadillo: An open source C++ algebra library for fast prototyping and computationally intensive experiments. Technical report, NICTA, 2010. URL http://arma.sf.net.
Oleg Sklyar, Duncan Murdoch, Mike Smith, Dirk Eddelbuettel, and Romain François. inline: Inline C, C++,
Fortran function calls from R, 2015. URL http://CRAN.R-Project.org/package=inline. R package
version 0.3.14.

14