File: Rcpp-package.Rnw

package info (click to toggle)
rcpp 0.11.3-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 9,948 kB
  • ctags: 16,427
  • sloc: ansic: 42,692; cpp: 34,078; makefile: 32; sh: 21
file content (479 lines) | stat: -rw-r--r-- 16,591 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
\documentclass[10pt]{article}
%\VignetteIndexEntry{Rcpp-package}
%\VignetteEngine{highlight::highlight}
%\VignetteKeywords{Rcpp, package}
%\VignetteDepends{Rcpp}

\usepackage[USletter]{vmargin}
\setmargrb{0.75in}{0.75in}{0.75in}{0.75in}
\usepackage{color,alltt}
\usepackage[authoryear,round,longnamesfirst]{natbib}

\usepackage[colorlinks]{hyperref}
\definecolor{link}{rgb}{0,0,0.3}	%% next few lines courtesy of RJournal.sty
\hypersetup{
    colorlinks,%
    citecolor=link,%
    filecolor=link,%
    linkcolor=link,%
    urlcolor=link
}

\usepackage{microtype}                     %% cf http://www.khirevich.com/latex/microtype/
\usepackage[T1]{fontenc}		   %% cf http://www.khirevich.com/latex/font/
\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/

\newcommand{\proglang}[1]{\textsf{#1}}
\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}}
\newcommand{\code}[1]{\texttt{#1}}
\newcommand{\rdoc}[2]{\href{http://www.rdocumentation.org/packages/#1/functions/#2}{\code{#2}}}

%% This corresponds to setting boxes=TRUE for highlight
\newsavebox{\hlbox}
\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137}
\definecolor{hlBd}{rgb}{0,0,0}
\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.9\textwidth}}%
    {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}}

<<version,echo=FALSE,print=FALSE>>=
prettyVersion <- packageDescription("Rcpp")$Version
prettyDate <- format(Sys.Date(), "%B %e, %Y")
require(Rcpp)
require(highlight)
@

\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois}
\title{Writing a package that uses \pkg{Rcpp} }
\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}}


\begin{document}
\maketitle

\abstract{
  \noindent This document provides a short overview of how to use
  \pkg{Rcpp}~\citep{CRAN:Rcpp,JSS:Rcpp,Eddelbuettel:2013:Rcpp} when writing
  an \proglang{R} package.  It shows how usage of the function
  \rdoc{Rcpp}{Rcpp.package.skeleton} which creates a complete and
  self-sufficient example package using \pkg{Rcpp}. All components of the
  directory tree created by \rdoc{Rcpp}{Rcpp.package.skeleton} are discussed
  in detail.  This document thereby complements the \textsl{Writing R
    Extensions} manual~\citep{R:Extensions} which is the authoritative source
  on how to extend \proglang{R} in general.  }

\section{Introduction}

\pkg{Rcpp}~\citep{CRAN:Rcpp,JSS:Rcpp,Eddelbuettel:2013:Rcpp} is an extension
package for \proglang{R} which offers an easy-to-use yet featureful interface
between \proglang{C++} and \proglang{R}.  However, it is somewhat different
from a traditional \proglang{R} package because its key component is a
\proglang{C++} library. A client package that wants to make use of the
\pkg{Rcpp} features must link against the library provided by \pkg{Rcpp}.

It should be noted that \proglang{R} has only limited support for
\proglang{C(++)}-level dependencies between packages~\citep{R:Extensions}. The
\texttt{LinkingTo} declaration in the package \texttt{DESCRIPTION} file
allows the client package to retrieve the headers of the target package (here
\pkg{Rcpp}), but support for linking against a library is not provided by
\proglang{R} and has to be added manually.

This document follows the steps of the \rdoc{Rcpp}{Rcpp.package.skeleton}
function to illustrate a recommended way of using \pkg{Rcpp} from a client
package. We illustrate this using a simple \proglang{C++} function
which will be called by an \proglang{R} function.

We strongly encourage the reader to become familiar with the material in the
\textsl{Writing R Extensions} manual~\citep{R:Extensions}, as well as with other
documents on \proglang{R} package creation such as \cite{Leisch:2008:Tutorial}. Given
a basic understanding of how to create \proglang{R} package, the present
document aims to provide the additional information on how to use \pkg{Rcpp}
in such add-on packages.

\section{Using \texttt{Rcpp.package.skeleton}}

\subsection{Overview}

\pkg{Rcpp} provides a function \rdoc{Rcpp}{Rcpp.package.skeleton}, modeled
after the base \proglang{R} function \rdoc{utils}{package.skeleton}, which
facilitates creation of a skeleton package using \pkg{Rcpp}.

\rdoc{Rcpp}{Rcpp.package.skeleton} has a number of arguments documented on
its help page (and similar to those of \rdoc{utils}{package.skeleton}). The
main argument is the first one which provides the name of the package one
aims to create by invoking the function.  An illustration of a call using an
argument \texttt{mypackage} is provided below.

<<tree,eval=FALSE>>=
Rcpp.package.skeleton("mypackage")
@
\begin{Hchunk}
\begin{verbatim}
$ ls -1R mypackage/
DESCRIPTION
NAMESPACE
R
Read-and-delete-me
man
src

mypackage/R:
RcppExports.R

mypackage/man:
mypackage-package.Rd
rcpp_hello_world.Rd

mypackage/src:
Makevars            ## up until Rcpp 0.10.6, see below
Makevars.win        ## up until Rcpp 0.10.6, see below
RcppExports.cpp
rcpp_hello_world.cpp
$
\end{verbatim}
\end{Hchunk}

Using \rdoc{Rcpp}{Rcpp.package.skeleton} is by far the simplest approach
as it fulfills two roles. It creates the complete set of files needed for a
package, and it also includes the different components needed for using
\pkg{Rcpp} that we discuss in the following sections.

\subsection{\proglang{C++} code}

If the \texttt{attributes} argument is set to
\texttt{TRUE}\footnote{Setting \texttt{attributes} to \texttt{TRUE} is the default. This document
does not cover the behavior of \texttt{Rcpp.package.skeleton} when \texttt{attributes} is set
to \texttt{FALSE} as we try to encourage package developpers to use
attributes. },
the following \proglang{C++} file is included in the \texttt{src/} directory:

<<lang=cpp>>=
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List rcpp_hello_world() {

    CharacterVector x = CharacterVector::create( "foo", "bar" )  ;
    NumericVector y   = NumericVector::create( 0.0, 1.0 ) ;
    List z            = List::create( x, y ) ;

    return z ;
}
@

The file defines the simple \texttt{rcpp\_hello\_world} function that
uses a few \pkg{Rcpp} classes and returns a \texttt{List}.

This function is preceded by the \texttt{Rcpp::export} attribute to automatically
handle argument conversion because \proglang{R} has to be taught how to
e.g. handle the \texttt{List} class.

\rdoc{Rcpp}{Rcpp.package.skeleton} then invokes \rdoc{Rcpp}{compileAttributes}
on the package, which generates the \texttt{RcppExports.cpp} file:

<<lang=cpp>>=
// This file was generated by Rcpp::compileAttributes
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

#include <Rcpp.h>

using namespace Rcpp;

// rcpp_hello_world
List rcpp_hello_world();
RcppExport SEXP mypackage_rcpp_hello_world() {
BEGIN_RCPP
    SEXP __sexp_result;
    {
        Rcpp::RNGScope __rngScope;
        List __result = rcpp_hello_world();
        PROTECT(__sexp_result = Rcpp::wrap(__result));
    }
    UNPROTECT(1);
    return __sexp_result;
END_RCPP
}
@

This file defines a function with the appropriate calling convention, suitable for
\rdoc{base}{.Call}. It needs to be regenerated each time functions
exposed by attributes are modified. This is the task of the
\rdoc{Rcpp}{compileAttributes} function. A discussion on attributes is
beyond the scope of this document and more information is available
in the attributes vignette \citep{CRAN:Rcpp:Attributes}.

\subsection{\proglang{R} code}

The \rdoc{Rcpp}{compileAttributes} also generates \proglang{R} code
that uses the \proglang{C++} function.

<<lang=cpp>>=
# This file was generated by Rcpp::compileAttributes
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393

rcpp_hello_world <- function() {
    .Call('mypackage_rcpp_hello_world', PACKAGE = 'mypackage')
}
@

This is also a generated file so it should not be modified manually, rather
regenerated as needed by \rdoc{Rcpp}{compileAttributes}.

\subsection{\texttt{DESCRIPTION}}

The skeleton generates an appropriate \texttt{DESCRIPTION} file, using
both \texttt{Imports:} and \texttt{LinkingTo} for \pkg{Rcpp}:

\begin{Hchunk}
\begin{verbatim}
Package: mypackage
Type: Package
Title: What the package does (short line)
Version: 1.0
Date: 2013-09-17
Author: Who wrote it
Maintainer: Who to complain to <yourfault@somewhere.net>
Description: More about what it does (maybe more than one line)
License: What Licence is it under ?
Imports: Rcpp (>= 0.11.0)
LinkingTo: Rcpp
\end{verbatim}
\end{Hchunk}

\rdoc{Rcpp}{Rcpp.package.skeleton} adds the three last lines to the
\texttt{DESCRIPTION} file generated by \rdoc{utils}{package.skeleton}.

The \texttt{Imports} declaration indicates \proglang{R}-level dependency
between the client package and \pkg{Rcpp}; code from the latter is being
imported into the package described here. The \texttt{LinkingTo} declaration
indicates that the client package needs to use header files exposed by
\pkg{Rcpp}.

\subsection{Now optional: \texttt{Makevars} and \texttt{Makevars.win}}

This behaviour changed with \pkg{Rcpp} release 0.11.0. These files used to be
mandatory, now they are merely optional. 

We will describe the old setting first as it was in use for a few years. The
new standard, however, is much easier and is described below.

\subsubsection{Releases up until 0.10.6}

Unfortunately, the \texttt{LinkingTo} declaration in itself was not
enough to link to the user \proglang{C++} library of \pkg{Rcpp}. Until more
explicit support for libraries is added to \proglang{R}, ones needes to manually
add the \pkg{Rcpp} library to the \texttt{PKG\_LIBS} variable in the
\texttt{Makevars} and \texttt{Makevars.win} files. (This has now changed with
release 0.11.0; see below).
\pkg{Rcpp} provides the unexported function \texttt{Rcpp:::LdFlags()} to ease the process:

\begin{Hchunk}
\begin{verbatim}
## Use the R_HOME indirection to support installations of multiple R version
PKG_LIBS = `$(R_HOME)/bin/Rscript -e "Rcpp:::LdFlags()"`

## As an alternative, one can also add this code in a file 'configure'
##
##    PKG_LIBS=`${R_HOME}/bin/Rscript -e "Rcpp:::LdFlags()"`
##
##    sed -e "s|@PKG_LIBS@|${PKG_LIBS}|" \
##        src/Makevars.in > src/Makevars
##
## which together with the following file 'src/Makevars.in'
##
##    PKG_LIBS = @PKG_LIBS@
##
## can be used to create src/Makevars dynamically. This scheme is more
## powerful and can be expanded to also check for and link with other
## libraries.  It should be complemented by a file 'cleanup'
##
##    rm src/Makevars
##
## which removes the autogenerated file src/Makevars.
##
## Of course, autoconf can also be used to write configure files. This is
## done by a number of packages, but recommended only for more advanced users
## comfortable with autoconf and its related tools.
\end{verbatim}
\end{Hchunk}


The \texttt{Makevars.win} is the equivalent, targeting windows.

\begin{Hchunk}
\begin{verbatim}
## Use the R_HOME indirection to support installations of multiple R version
PKG_LIBS = $(shell "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" -e "Rcpp:::LdFlags()")
\end{verbatim}
\end{Hchunk}

\subsubsection{Releases since 0.11.0}

As of release 0.11.0, this is no longer needed as client packages obtain the
required code from \pkg{Rcpp} via explicit function registration. The user
does not have to do anything.  

This means that \code{PKG\_LIBS} can now be empty---unless some client
libraries are needed.  For example, \pkg{RcppCNPy} needs compression support
and hence uses \code{PKG\_LIBS= -lz}. Similarly, when a third-party library is
required, it can and should be set here.

\subsection{\texttt{NAMESPACE}}

The \rdoc{Rcpp}{Rcpp.package.skeleton} function also creates a file
\texttt{NAMESPACE}.

\begin{Hchunk}
\begin{verbatim}
useDynLib(mypackage)
exportPattern("^[[:alpha:]]+")
importFrom(Rcpp, evalCpp)
\end{verbatim}
\end{Hchunk}

This file serves three purposes. First, it ensure that the dynamic library
contained in the package we are creating via
\rdoc{Rcpp}{Rcpp.package.skeleton} will be loaded and thereby made
available to the newly created \proglang{R} package. 

Second, it declares which functions should be globally visible from the
namespace of this package. As a reasonable default, we export all functions.

Third, it instructs R to import a symbol from \pkg{Rcpp}. This sets up the
import of all registered function and, together with the \code{Imports:}
statement in \code{DESCRIPTION}, provides what is needed for client packages
to access \pkg{Rcpp} functionality.

\subsection{Help files}

Also created is a directory \texttt{man} containing two help files. One is
for the package itself, the other for the (single) \proglang{R} function
being provided and exported.

The \textsl{Writing R Extensions} manual~\citep{R:Extensions} provides the complete
documentation on how to create suitable content for help files.

\subsubsection{\texttt{mypackage-package.Rd}}

The help file \texttt{mypackage-package.Rd} can be used to describe
the new package.

\begin{Hchunk}
\begin{verbatim}
\name{mypackage-package}
\alias{mypackage-package}
\alias{mypackage}
\docType{package}
\title{
What the package does (short line)
}
\description{
More about what it does (maybe more than one line)
~~ A concise (1-5 lines) description of the package ~~
}
\details{
\tabular{ll}{
Package: \tab mypackage\cr
Type: \tab Package\cr
Version: \tab 1.0\cr
Date: \tab 2013-09-17\cr
License: \tab What license is it under?\cr
}
~~ An overview of how to use the package, including the most important functions ~~
}
\author{
Who wrote it

Maintainer: Who to complain to <yourfault@somewhere.net>
}
\references{
~~ Literature or other references for background information ~~
}
~~ Optionally other standard keywords, one per line, from file KEYWORDS in the R documentation directory ~~
\keyword{ package }
\seealso{
~~ Optional links to other man pages, e.g. ~~
~~ \code{\link[<pkg>:<pkg>-package]{<pkg>}} ~~
}
\examples{
%% ~~ simple examples of the most important functions ~~
}
\end{verbatim}
\end{Hchunk}

\subsubsection{\texttt{rcpp\_hello\_world.Rd}}

The help file \texttt{rcpp\_hello\_world.Rd} serves as documentation for the
example \proglang{R} function.

\begin{Hchunk}
\begin{verbatim}
\name{rcpp_hello_world}
\alias{rcpp_hello_world}
\docType{package}
\title{
Simple function using Rcpp
}
\description{
Simple function using Rcpp
}
\usage{
rcpp_hello_world()
}
\examples{
\dontrun{
rcpp_hello_world()
}
}
\end{verbatim}
\end{Hchunk}

\section{Using modules}

This document does not cover the use of the \texttt{module} argument
of \rdoc{Rcpp}{Rcpp.package.skeleton}. It is covered
in the modules vignette \citep{CRAN:Rcpp:Modules}.

\section{Further examples}

The canonical example of a package that uses \pkg{Rcpp} is the
\pkg{RcppExamples} \citep{CRAN:RcppExamples} package. \pkg{RcppExamples}
contains various examples of using \pkg{Rcpp}. Hence, the \pkg{RcppExamples}
package is provided as a template for employing \pkg{Rcpp} in packages.

Other CRAN packages using the \pkg{Rcpp} package are \pkg{RcppArmadillo}
\citep{CRAN:RcppArmadillo},
and \pkg{minqa} \citep{CRAN:minqa}. Several other packages follow older (but still supported
and appropriate) instructions. They can serve examples on how to get data to
and from \proglang{C++} routines, but should not be considered templates for
how to connect to \pkg{Rcpp}. The full list of packages using \pkg{Rcpp} can
be found at the \href{http://CRAN.R-project.org/package=Rcpp}{CRAN page} of
\pkg{Rcpp}.

\section{Other compilers}

Less experienced \proglang{R} users on the Windows platform frequently ask
about using \pkg{Rcpp} with the Visual Studio toolchain.  That is simply not
possible as \proglang{R} is built with the \pkg{gcc} compiler. Different
compilers have different linking conventions. These conventions are
particularly hairy when it comes to using \proglang{C++}.  In short, it is
not possible to simply drop sources (or header files) from \pkg{Rcpp} into a
\proglang{C++} project built with Visual Studio, and this note makes no
attempt at claiming otherwise.

\pkg{Rcpp} is fully usable on Windows provided the standard Windows
toolchain for \proglang{R} is used. See the \textsl{Writing R Extensions}
manual~\citep{R:Extensions} for details.

\section{Summary}

This document described how to use the \pkg{Rcpp} package for \proglang{R}
and \proglang{C++} integration when writing an \proglang{R} extension
package. The use of the \rdoc{Rcpp}{Rcpp.package.skeleton} was shown in
detail, and references to further examples were provided.

\bibliographystyle{plainnat}
\bibliography{Rcpp}

\end{document}