Unofficial Rcpp API Documentation
Warning: This post is a work in progress. It will periodically be updated as time permits.
Introduction
The following unofficial API documentation for Rcpp is based off some personal notes and teaching materials that I have prepared over the years of working with Rcpp. I’ve attempted to reformat the notes in the form of Armadillo’s API, which I think are some of the best documentation out there for a C++ matrix library. At some point, when the documentation becomes a bit more stable or if there is larger contributor interest, I will likely attempt to merge this into the Rcpp project so that a docs subdomain could hopefully be added to http://rcpp.org.
Please note: The post is written using RMarkdown for maximum flexibility.
API Documentation for Rcpp 0.12.11
Preamble

The goal of the API documentations are to provide a public facing concise view of Rcpp features. As a result, the documentation will be somewhat long. To help navigate the documentation, it has been split into different section. Furthermore, one should use the built in search functionality to search text for keywords using either
CNTRL
+F
on Windows and Linux orCMD
+F
on macOS. 
Presently, any contribution to this document may be down by a pull request (PRs) on GitHub.

Please report any bugs to the Rcpp Core Team.
Overview
 Vector, Matrix, List, DataFrame
 Member functions
 Sugar
 Exception Handling
 Environment, Function, Language
 XPtr
 S4 classes / modules
Vector, Matrix, List, and DataFrame Classes
Vector<RTYPE>, NumericVector, IntegerVector, …  Vector class 
Matrix<RTYPE>, NumericMatrix, IntegerMatrix, …  Matrix class 
List  List typedef 
DataFrame  Data frame class 
RObject  RObject class 
Member functions
Operators  Mathematical (add, subtract, etc) and logical (inequalities) 
Dimensional Information  Size attribute information 
Element Access  Retrieving element values with and without bounds check 
Subset Views  Subset data structures 
Iterators  Random access iterators 
STLstyle Container Functions  Standard Library styled functions 
Static Member Functions  Set of member functions persistant across instances 
Exception Handling
stop 
Stop execution 
warning 
Send Warning to console 
Rcout<< 
Write message to console 
not_a_matrix 
Object is not a matrix 
parse_error 
Unable to parse values 
not_s4 
Not a valid S4 class 
not_reference 
Object not a reference 
not_initialized 
Object not initialized 
no_such_slot 
S4 Object lacks slot 
no_such_field 
Exception not used 
not_a_closure 
Object not a closure 
no_such_function 
No such function 
unevaluated_promise 
Promise not yet evaluated 
S4_creation_error 
Error creating object of S4 class 
reference_creation_error 
Exception not used 
no_such_binding 
No such binding 
binding_not_found 
Binding not found 
binding_is_locked 
Binding is locked 
no_such_namespace 
No such namespace 
function_not_exported 
Function not exported 
eval_error 
Evaluation error 
not_compatible 
Not a compatible transformation 
index_out_of_bounds 
Request index is out of bounds 
Sugar
ifelse 
Vectorized Ifelse 
is_false 
Is Value False? 
is_true 
Is Value True? 
any 
At Least One Value is True 
all 
All Values Must be True 
Re 
Real Values of Complex Number 
Im 
Imaginary Values of Complex Number 
Mod 
Modulus (r) 
Arg 
Arg (theta) 
Conj 
Complex Conjugate 
head 
View the First n Values 
tail 
View the Last n Values 
abs 
Absolute Value 
sqrt 
Square Root 
pow 
Raise to the n^th^ Power 
sum 
Summation 
sign 
Extract the Sign of Values 
diff 
Lagged Difference 
cumsum 
Cumulative Sum 
cumprod 
Cumulative Product 
cummin 
Cumulative Minimum 
cummax 
Cumulative Maximum 
sin 
Sine 
cos 
Cosine 
tan 
Tangent 
asin 
Arc Sine 
acos 
Arc Cosine 
atan 
Arc Tangent 
sinh 
Hyperbolic Sine 
cosh 
Hyperbolic Cosine 
tanh 
Hyperbolic Tangent 
log 
Natural Logarithms 
exp 
Expoential 
log10 
Base 10 Logarithm 
log1p 
Natural Logarithm $log(1+x)$ 
expm1 
$\exp(x)  1$ 
sample 
Randomly sample values 
ceiling ,ceil 
Smallest integer greater than or equal to x 
trunc 
Truncates the values in x toward 0 
floor 
Largest integer less than or equal to x 
round 
Round values to specified decimal place 
signif 
Rounds values to number of significant digits 
Finite, Infinite and NaN Detection
predefined 
Predefined NA/NaN/Inf Constants 
is_na 
Detects if values are missing 
is_nan 
Detects if values are not a number (NaN ) 
is_finite 
Detects if value is finite 
is_infinite 
Detects if value is infinite 
na_omit 
Remove NA and NaN values 
noNA 
Assert that the object is NA free 
sapply 
Apply a function to one input and store results in vector 
lapply 
Apply a function to one input and store results in list 
mapply 
Apply a function to multiple inputs and store results in vector 
Special Functions of Mathematics
factorial 
Factorial 
lfactorial 
Factorial Logarithm 
choose 
Combination 
lchoose 
Combination Logarithm 
beta 
Beta Function 
lbeta 
Natural Log Beta Function 
gamma 
Gamma Function 
lgamma 
Natural Log Gamma Function 
psigamma 
General Gamma Derivative 
digamma 
Second Gamma Derivative 
trigamma 
Third Gamma Derivative 
tetragamma 
Fourth Gamma Derivative 
pentagamma 
Fifth Gamma Derivative 
min 
Minimum Value 
max 
Maximum Value 
range 
Range 
mean 
Mean Value 
median 
Median Value 
var 
Variance 
sd 
Standard Deviation 
rev 
Reverse ordering of a vector 
pmax 
Parallel maximum value 
pmin 
Parallel minimum value 
clamp 
Values between a minimum and maximum 
which_max 
Index of the maximum value 
which_min 
Index of the minimum value 
match 
Find indices of the first value in a separate vector 
self_match 
Find indices of the first occurrence of each value in a vector 
in 
Determine if a match was located for each element of A in B 
unique 
Obtain the unique values 
duplicated 
Obtain a logical vector indicating the duplicate values 
sort_unique 
Obtain the unique values and sort them 
table 
Create a frequency table of occurrences 
setequal 
Equality of Set Values 
intersect 
Intersection of Set Values 
union_ 
Union of Set Values 
setdiff 
Asymmetric Difference of Set Values 
colSums 
Column Sums of a Matrix 
rowSums 
Row Sums of a Matrix 
colMeans 
Column Means of a Matrix 
rowMeans 
Row Means of a Matrix 
outer 
Outer Product of Arrays on a Function 
lower_tri 
Extract the Lower Triangle Part of a Matrix 
upper_tri 
Extract the Upper Triangle Part of a Matrix 
diag 
Extract the Diagonal Portion of a Matrix 
row 
Create a matrix of Row Indexes 
col 
Create a matrix of Column Indexes 
cbind 
Create matrix by combing column vectors 
seq_along 
Generate an R index sequence given a vector 
seq_len 
Generate an R index sequence given an integer 
rep 
Replicate vector $N$ times 
rep_each 
Replicate each element in line $N$ times 
rep_len 
Replicate values until vector is of length $N$ 
collapse 
Collapse multiple strings into one string 
trimws 
Trim leading and/or trailing whitespace from strings 
p/d/q/rbinom 
Binomial 
p/d/q/rgeom 
Geometric 
p/d/q/rhyper 
Hypergeometric 
p/d/q/rnbinom 
Negative Binomial 
p/d/q/rpois 
Poisson 
p/d/q/rwilcox 
Wilcoxon 
p/d/q/rsignrank 
Wilcoxon Signed Rank 
p/d/q/rbeta 
Beta 
p/d/q/rcauchy 
Cauchy 
p/d/q/rchisq 
Chisquare 
p/d/qnchisq 
Noncentral Chisquare 
p/d/q/rexp 
Exponential 
p/d/q/rf 
F 
p/d/qnf 
Noncentral F 
p/d/q/rgamma 
Gamma 
p/d/q/rnorm 
Normal 
p/d/q/rlnorm 
Log Normal 
p/d/q/rlogis 
Logistic 
p/d/q/rt 
Student’s T 
p/d/q/runif 
Uniform 
p/d/q/rweibull 
Weibull 
Vector, Matrix, List, and DataFrame Classes
Vector

The templated
Vector
class is a one dimensional arraylike structure providing storage for homogenous data types, with an interface similar to that ofstd::vector
. Being an implementation of policybased design, much of the behavior ofVector
is determined by the policy classes it inherits fromRObjectMethods
StoragePolicy
SlotProxyPolicy
AttributeProxyPolicy
NamesProxyPolicy
as well as the CRTP base class
VectorBase
. This type is instantiated asVector<RTYPE>
, whereRTYPE
is one of the following validSEXPTYPE
s:REALSXP
INTSXP
CPLXSXP
LGLSXP
STRSXP
VECSXP
RAWSXP
EXPRSXP

For convenience, the following
typedefs
have been defined in theRcpp
namespace:NumericVector
=Vector<REALSXP>
DoubleVector
=Vector<REALSXP>
RawVector
=Vector<RAWSXP>
IntegerVector
=Vector<INTSXP>
ComplexVector
=Vector<CPLXSXP>
LogicalVector
=Vector<LGLSXP>
CharacterVector
=Vector<STRSXP>
StringVector
=Vector<STRSXP>
GenericVector
=Vector<VECSXP>
List
=Vector<VECSXP>
ExpressionVector
=Vector<EXPRSXP>

Within this documentation, the default type used will be
NumericVector
unless another data type is required to show a specific feature.  Constructors:
Vector()
Vector(SEXP x)
Vector(const int &size, const stored_type &u)
Vector(const std::string &st)
Vector(const char *st)
Vector(const Vector &other)
Vector(const int &size)
Vector(const Dimension &dims)
Vector(const Dimension &dims, const U &u)
Vector(const Vector &other)

By default, the vectors constructed from dimensions will always be initialized with all entries being zero (
0
) or an empty string (""
). 
For the majority of cases, the interface being used is that of the R to C++ interface that relies upon the
Vector(SEXP x)
constructor, which establishes a pointer to the underlying data. That is, theVector
object points to the memory location of theSEXP
R object in order to avoid copying the data into C++. The only exception to this rule is if the data passed is of a different type in which case a deep copy is performed before a pointer is established. For example, ifnumeric()
data is passed toNumericVector
the correct handoff occurs. However, ifinteger()
data were to be passed to aNumericVector
aclone()
would be made to typenumeric()
which has its pointer then assigned to theNumericMatrix
.  Examples:
Matrix

The main class for matrices is the templated
Matrix
class, which derives from a combination of both theVector
andMatrixBase
types. Like theVector
class,Matrix
uses the policybased design pattern to manage the lifetime of its undelyingSEXP
via the template parameterStoragePolicy
, which uses thePreserveStorage
policy class by default. Matrices are
instantiated asMatrix<RTYPE>
, where the valueRTYPE
is one of the followingSEXPTYPE
s:REALSXP
INTSXP
CPLXSXP
LGLSXP
STRSXP
VECSXP
RAWSXP
EXPRSXP

For convenience, the following
typedefs
have been defined in theRcpp
namespace:NumericMatrix
=Matrix<REALSXP>
RawMatrix
=Matrix<RAWSXP>
IntegerMatrix
=Matrix<INTSXP>
ComplexMatrix
=Matrix<CPLXSXP>
LogicalMatrix
=Matrix<LGLSXP>
CharacterMatrix
=Matrix<STRSXP>
StringMatrix
=Matrix<STRSXP>
GenericMatrix
=Matrix<VECSXP>
ListMatrix
=Matrix<VECSXP>
ExpressionMatrix
=Matrix<EXPRSXP>

Within this documentation, the default type used will be
NumericMatrix
unless another data type is required to show a specific feature.  Constructors:
Matrix()
Matrix(SEXP x)
Matrix(const int& nrows_, const int& ncols)
Matrix(const int& nrows_, const int& ncols, Iterator start)
Matrix(const int& n)
Matrix(const Matrix& other)

By default, the matrices constructed from dimensions will always be initialized with all entries being zero (
0
) or empty strings (""
) 
For the majority of cases, the interface being used is that of the R to C++ interface that relies upon the
Matrix(SEXP x)
constructor, which establishes a pointer to the underlying data. That is, theVector
object points to the memory location of theSEXP
R object in order to avoid copying the data into C++. The only exception to this rule is if the data passed is of a different type in which case a deep copy is performed before a pointer is established. For example, ifnumeric()
data is passed toNumericMatrix
the correct handoff occurs. However, ifinteger()
data were to be passed to aNumericMatrix
aclone()
would be made to typenumeric()
which has its pointer then assigned to theNumericMatrix
.  Examples:
List

The
List
data structure is atypedef
of templatedVector
class based on theRTYPE
ofVECSXP
that provides heterogenous storage class. As a result, theList
class acts as a generic storage object that can simultaneously hold multiple differentRTYPE
structures.  Constructors:
List()
List(SEXP x)
List(const int &size, const stored_type &u)
List(const std::string &st)
List(const char *st)
List(const Vector &other)
List(const int &size)
List(const Dimension &dims)
List(const Dimension &dims, const U &u)
List(const Vector &other)

Unlike the
Vector
class, theList
constructed from dimensions will have aNULL
value set for each element unless a value is otherwise assigned.  Examples:
DataFrame

The
DataFrame
data structure is a typedef of theDataFrame_Impl
class, which is a special extension of the templatedVector
class that allows for a collection of heterogenousVector
’s of the same length. As the crux of the implementation of is policybased design focused, much of the behavior ofDataFrame
is determined by the policy classes it inherits fromRObjectMethods
StoragePolicy
SlotProxyPolicy
AttributeProxyPolicy
NamesProxyPolicy
as well as the CRTP base class
VectorBase
. 
Constructors:
DataFrame()
 DataFrame(SEXP x)
 DataFrame(const DataFrame &other)
 DataFrame(const T &obj)

Caveat: All
DataFrame
columns must be named. Failure to name the columns will result in the run time error of:not compatible with STRSXP
since Rcpp uses an internal call to R to create the
DataFrame
. 
Examples:
RObject

The
RObject
data structure is a typedef of theRObject_Impl
class. Principally, the class can be viewed as the glue of Rcpp due to policybased design principles. In turn, theRObject
class really acts as a “shell” that stores properties of the following policies:PreserveStorage
: Member functions that provide theSEXP
R object alongside ways to modify and update the object.SlotProxyPolicy
: Member functions related to only manipulating S4 objects.AttributeProxyPolicy
: Member functions that modify attribute information of the R object.RObjectMethods
: Member functions that provide descriptors of the R object such as type, object oriented programming (S3/S4) system, andNULL
status.

Constructors:
RObject()
 RObject(const RObject &other)
 RObject(const GenericProxy<Proxy> &proxy)
 Examples:
 See also:
Member Functions
Operators

Operators allow for operations to take place between two different
Vector
orMatrix
objects. The operations are defined to works in an elementwise fashion where applicable. 
Viable mathematical operations that are able to be performed.
Operation  Definition  VectorVector  VectorScalar  VectorMatrix  Matrix  Matrix  Matrix  Scalar 

+  Addition  Yes  Yes  No  No  Yes 
  Subtraction  Yes  Yes  No  No  Yes 
/  Division  Yes  Yes  No  No  Yes 
*  Multiplication  Yes  Yes  No  No  Yes 
 Logical Operations
Operation  Definition  VectorVector  VectorScalar  VectorMatrix  Matrix  Matrix  Matrix  Scalar 

==  Equality  Yes  Yes  No  No  Yes 
!=  Nonequality  Yes  Yes  No  No  Yes 
>=  Greater than or equal to  Yes  Yes  No  No  Yes 
<=  Less than or equal to  Yes  Yes  No  No  Yes 
<  Less than  Yes  Yes  No  No  Yes 
>  Greater than  Yes  Yes  No  No  Yes 
!  Negate  Yes  Yes  No  No  Yes 
 Examples:
Dimensional Information
.nrow() ,.rows() 
number of rows in a Matrix , DataFrame 
.ncol() ,.cols() 
number of columns in a Matrix , DataFrame 
.size() ,.length() 
number of items in a Matrix , Vector 

Return type is that of an
int
,unsigned int
, orR_xlen_t

Note: As of Rcpp 0.13.0, new size attribute accessors were added to the
DataFrame
class that mimick those available inMatrix
. Previously, to obtain the number of columns, one would have to use the.size()
or.length()
member function. In addition, the number of observations previously had to be obtained by.nrows()
. 
Examples:
Element Access

Described within this section is the ability to access elements using the position, categorical, and logical indexing systems.
 The access system provides two retrieval methods for all classes
that differ in computational time to obtain values from objects.
 The preferred method to access elements is
()
, which that takes slightly longer due to a bounds check being performed that verifies whether the requested element is within the access scope. Furthermore, if the requested element is out of bounds, an exception is raised and the program stops.  The other method uses
[]
, which does not perform a bounds check and assumes that the access scope is valid. If an element is out of bounds, the behavior exhibited will be undefined and may cause havoc with later parts of a procedure. Only use this form of accessor if the procedure has been thoroughly tested and debugged.
 The preferred method to access elements is
 Note: Using accessors without a bounds check is not recommended unless the code has been thoroughly tested as undefined behavior (UB) may emerge. UB is very problematic.
Position Access
 Access a single element or object using a positional index.
(i)
provides the ith element or object in addition to performing a bounds check that ensures the requested index is a valid location.[i]
similar to the previous case, but does so without a bounds check.at(i,j)
provides the i,jth element of aMatrix
with a bounds check.(i,j)
provides the i,jth element of aMatrix
without a bounds check.

Caveat: Using either
[i]
or(i)
onList
andDataFrame
, provides the object (e.g.Vector
) at position i whereas the use onVector
orMatrix
will provide a scalar element (e.g.double
). 
Note: Unlike R, there is no
[]
subset operator for matrices with C++. The reason for the lack ofoperator[]
relates to a fundamental design choice made by the creators of C++ related to the presence of theoperator,
. In essence, after the complete evaluation of the first coordinatex
and disposal of the results, only then is the second coordinatey
able to be evaluated. Unfortunately, this yields the followingWall
issue:left operand of comma operator has no effect.
Therefore, the only viable matrix subset operators within C++ are
operator()
andoperator at()
provide subset operations.  Examples:
Categorical Access
 Access element by name within a
Vector
,List
, orDataFrame
.(NAME)
provides the element associated with theNAME
in addition to performing a bounds check that ensures the requestedNAME
exists.[NAME]
similar to the previous case, but does so without a bounds check.
 Examples:
Logical Access
 Access element by boolean values within a
Vector
,List
, orDataFrame
.(BOOL)
provides only the elements associatedtrue
logical condition in addition to performing a bounds check that ensures the requested element at theBOOL
location exists.[BOOL]
similar to the previous case, but does so without a bounds check.

Caveat: The
BOOL
must be aLogicalVector
of equal size to the object being subset.  Examples:
Subset Views
Iterators

C++ Standard Template Library (STL) styled random access iterators exist underlying the
Vector
andMatrix
classes. 
Iterator accessor:
·begin() 
pointer to the start of the vector 
·end() 
pointer to one past end of vector 
 Kinds of Iterators:
NumericVector::iterator 
allows for read/write access to elements (stored by column) 
ComplexVector::iterator 

IntegerVector::iterator 

LogicalVector::iterator 

CharacterVector::iterator 

RawVector::iterator 

ExpressionVector::iterator 

GenericVector::iterator 

NumericMatrix::iterator 

ComplexMatrix::iterator 

IntegerMatrix::iterator 

RawMatrix::iterator 

LogicalMatrix::iterator 

CharacterMatrix::iterator 

StringMatrix::iterator 

ExpressionMatrix::iterator 

GenericMatrix::iterator 

ListMatrix::iterator 
NumericVector::const_iterator 
allows for read access to elements (stored by column) 
ComplexVector::const_iterator 

IntegerVector::const_iterator 

LogicalVector::const_iterator 

CharacterVector::const_iterator 

RawVector::const_iterator 

ExpressionVector::const_iterator 

GenericVector::const_iterator 

NumericMatrix::const_iterator 

ComplexMatrix::const_iterator 

IntegerMatrix::const_iterator 

RawMatrix::const_iterator 

LogicalMatrix::const_iterator 

CharacterMatrix::const_iterator 

StringMatrix::const_iterator 

ExpressionMatrix::const_iterator 

GenericMatrix::const_iterator 

ListMatrix::const_iterator 
STLstyle container functions

There exists a special class of member functions that mimic how C++ Standard Template Library (STL) implement member functions for container architecture such as
vector
,deque
, andlist
. 
Member functions that do not alter the size of the Rcpp object
Member  Description 

operator() 
Access elements with checking range 
operator[] 
Access elements without checking range 
.length() , .size() 
Amount of elements in the collection 
.fill(u) 
Fill the collection with element u 
 Member functions that do alter the size of the Rcpp object and result in the object being recreated.
Member  Description 

·push_back(x) 
Insert x at end of vector, grows vector 
·push_front(x) 
Insert x at beginning of vector, grows vector 
·insert(i, x) 
Insert x at the i^th^ position of, grows vector 
·erase(i) 
Remove element at i^th^ position, shrinks vector 
 Warning: Using any function to grow or shrink an Rcpp object results in the data being copied from the original object into a new object. As a result, there will be a severe degregation of performance. Therefore, it is highly recommended to convert the Rcpp object to an STL object that can easily be grown or shrunk if the sample size is not known in advance.
Static Member Functions
create
::create(X, Y) 
::create(X, Y, …) 
::create(X, Y, …)

Initializes a
Vector
,List
, orDataFrame
by combining objects together sequentially in a manner similar toc(1, 2)
in R.  In the case of a
Vector
, the values X and Y must be an atomic value of the same underlying type T, where T is one of the following:int
double
std::complex<double> / Rcomplex
bool

For either a
DataFrame
orList
, X, Y are allowed to be any combination ofVector
,Matrix
, and the previously mentioned supported atomic types. 
create
is defined for any number of arguments between 1 and 20, inclusive. 
When constructing examples, it is often preferable to use
create
method to build a vector.  Examples:
get_na()

Obtain the correct missing value constant for the given RTYPE associated with the Rcpp data structure.

Examples:
 See also:
is_na()

Determine whether an element within the Rcpp data structure matches a missing constant of the given RTYPE.

Examples:
import(InputIterator first, InputIterator last)
import_transform(InputIterator first, InputIterator last, F f)
diag(int size, const U &diag_value)

This method is available only for the
Matrix
class. 
Examples:
eye(int n)

This method is available only for the
Matrix
class. 
Examples:
ones(int n)

This method is available only for the
Matrix
class. 
Examples:
zeros(int n)

This method is available only for the
Matrix
class. 
Examples:
Environment
Function
Language
XPtr
S4 Classes
Exception Handling
External Exception Classes
Internal Exception Classes
Simple Exceptions
Exceptions
Advanced exceptions
Sugar

The objective behind Rcpp sugar is to provide a subset of the highlevel R syntax in C++. For instance, part of the functionality behind the
table( X )
function can be 
Unless otherwise noted, if a
Matrix
is supplied, then theMatrix
is corcered into columnform vectors before having the sugar functional procedure performed. For example, given a 2x2 matrix the results of the function call will go R1C1, R2C1, R1C2, and R2C2 where R stands for Row and C for column.
Logical Operations
 Boolean functions that provide a way to analyze the data are provided within.
ifelse( CONDITION, TRUEVAL, FALSEVAL)

Vectorized
ifelse
assignment of elements dependent on theCONDITION
beingtrue
(TRUEVAL
) orfalse
(FALSEVAL
).  To use the vectorized
ifelse
the following criteria must be met:CONDITION
: ALogicalVector
or a sugar expression that evalutes to aLogicalVector
TRUE
/FALSE
: either two compatible sugar expression (same RTYPE, same length), OR
 one sugar expression and one compatible primitive (same RTYPE)
 Caveat: Unlike the R equivalent, there is no recycling the occurs if the vectors are of different lengths. In said cases, an error will be raised at runtime indicating the length difference.
Single Logical Result
is_true( X )  is_false( X ) 

Convert the result state of
any( CONDITION )
andall( CONDITION )
from theSingleLogicalResult
template class to an atomic valuebool
evaluated as eithertrue
orfalse
dependent on whether the call tois_true( X )
oris_false( X )
is matched. 
For example, if
any( CONDITION )
evaluates tofalse
thanis_true( X )
will returnfalse
butis_false( X )
will returntrue
. 
Examples:
all( X )

Tests if all elements in a
LogicalVector
orLogicalMatrix
aretrue
. 
The actual return type of
all(X)
is an instance of theSingleLogicalResult
template class, but the functionsis_true
andis_false
may be used to convert the return value tobool
. 
Examples:
any( X )

Tests if any elements in a
LogicalVector
orLogicalMatrix
aretrue
. 
The actual return type of
any(X)
is an instance of theSingleLogicalResult
template class, but the functionsis_true
andis_false
may be used to convert the return value tobool
. 
Examples:
Complex Operators
Complex Components
Re( X )  Im( X ) 

Extract the real or imaginary component of a complex number.

Definition: , where $x, y \in \mathbb{R}$.

X must be stored within a
Vector
orMatrix
of typeComplex
. The return type is aNumericVector
regardless of whether aVector
orMatrix
is supplied. 
Example:
 See also:
Mod( X )

Compute the modulus of a complex number or the length from the origin to the point represented in the complex plane (radius in polar coordinates).

Definition:

X must be stored within a
Vector
orMatrix
of typeComplex
. The return type is aNumericVector
regardless of whether aVector
orMatrix
is supplied. 
Example:
 See also:
Arg( X )

Compute the argument of a complex number or the angle from the positive side of the real axis to the line segment connecting the origin and the point in the complex plane (theta in polar coordinates).

Definition:

X must be stored within a
Vector
orMatrix
of typeComplex
. The return type is aNumericVector
regardless of whether aVector
orMatrix
is supplied. 
Example:
 See also:
Conj( X )

Compute the complex conjugate of a complex number or a number with an equivalent real component by negated imaginary component.

X must be stored within a
Vector
orMatrix
of typeComplex
. The return type is aComplexVector
regardless of whether aVector
orMatrix
is supplied. 
Example:
Data Operations
First or Last Elements
head( X , n )  tail( X , n ) 

Obtain the first or last n observations using
head
ortail
. 
All types of a
Vector
orMatrix
are supported. 
Example:
abs( X )

Obtain the absolute value of all elements.

Definition:

Supported types to perform the operation are
Numeric
orInteger
of aVector
orMatrix
. 
Example:
sqrt( X )

Compute the square root of all elements.

Definition:

Supported types to perform the operation are
Numeric
,Integer
, orComplex
of aVector
orMatrix
. 
Example:
pow( X , n)

Obtain the power of the i^th^ element raised to the n power.

Definition:

Supported types to perform the operation are
Numeric
orInteger
of aVector
orMatrix
. 
Caveat: Only X is able to be vectorized. The value of n must be a scalar of
int
ordouble
type. 
Example:
sum( X )

Calculate the overall summation of all elements.

Definition:

Supported types to perform the operation are
Numeric
orInteger
of aVector
orMatrix
. 
Example:
 See also:
sign( X )

Determine the sign of a number or whether a number is positive, negative, or zero.

Definition:

Supported types are
Numeric
orInteger
of aVector
orMatrix
. 
Example:
diff( X )

Obtain the difference between sucessive
Vector
elements by $(i+1)$^th^ and the i^th^ element. 
Definition:

Supported types are
Numeric
orInteger
of aVector
orMatrix
. 
Example:
Cumulative Arithmetic
cumsum( X )  cumprod( X ) 

Calculates the cumulative sum (
cumsum
) or cumulative product (cumprod
) of aVector
orMatrix
X. 
If an
NA
value is encountered, it will be propagated throughout the remaining elements in the result vector. 
For
cumsum
, X should be anInteger
orNumeric
Vector
orMatrix
. 
For
cumprod
, X should be anInteger
,Numeric
, orComplex
Vector
orMatrix
. 
In either case, the return type is a
Vector
of the same underlyingSEXPTYPE
as the input. 
Caveat: at the time of writing (Rcpp version 0.12.11), not all Sugar expressions are directly compatible with
Vector::operator=
, as many of these functions return intermediate template classes which require an explicit conversion to
Vector
, rather than directly returning aVector
. In such cases the user may need to “help” the compiler with the conversion by Constructing a
Vector
from the result, and assigning that to the targetVector
; or  Calling an explicit conversion member function of the Sugar class, if such a function exists.
See the examples below for a demonstration.
 Constructing a

Examples:
Cumulative Extremum
cummax( X )  cummin( X ) 

Calculates the cumulative maximum (
cummax
) or cumulative minimum (cummin
) of aVector
orMatrix
X. 
If an
NA
value is encountered, it will be propagated throughout the remaining elements in the result vector. 
Supported types are
Integer
orNumeric
of aVector
orMatrix
. 
Caveat: at the time of writing (Rcpp version 0.12.11), not all Sugar expressions are directly compatible with
Vector::operator=
, as many of these functions return intermediate template classes which require an explicit conversion to
Vector
, rather than directly returning aVector
. In such cases the user may need to “help” the compiler with the conversion by Constructing a
Vector
from the result, and assigning that to the targetVector
; or  Calling an explicit conversion member function of the Sugar class, if such a function exists.
See the examples below for a demonstration.
 Constructing a

Examples:
trigonometric elementwise functions
sin( X )  asin( X )  sinh( X ) 
cos( X )  acos( X )  cosh( X ) 
tan( X )  atan( X )  tanh( X ) 

Compute the trigonometric value for each element in a given structure.
 Usage:
vector_type Y = func(X)
X
andY
must be of the samevector_type
/matrix_type
. where
func
is one of the following trigonmetric functions: sin family:
sin(X)
,asin(X)
,sinh(X)
 cos family:
cos(X)
,acos(X)
,cosh(X)
 tan family:
tan(X)
,atan(X)
,tanh(X)
 sin family:

Supported types are
Integer
,Numeric
, orComplex
of aVector
orMatrix
.  Examples:
Logarithms and Exponentials
log( X )  log10( X )  log1p( X ) 
exp( X )  expm1( X ) 

Apply a function to each element
 Usage:
vector_type Y = func(X)
X
andY
must be of the samevector_type
/matrix_type
.
 Traditional use case:
log( X )
computes the natural logarithm sometimes representated as $\ln(X)$log10( X )
computes the base 10 logarithm.exp( X )
computes the exponential function given by:
 Special use cases:

log1p( X )
computes $\log( 1 + X )$ accurately for $\leftX\right « 1$. 
expm1( X )
computes $\exp( X )  1$ accurately for $\leftX\right « 1$.

 Examples:
sample
sample( n , size , replace , probs ) 
sample( X , size , replace , probs ) 

Obtain a random sampling of elements from either a positive number of elements ranging from 1 to n or data contained with X.

All types are supported of a
Vector
orMatrix
.  The parameters available for
sample
are defined as:size
, the number of items to samplereplace = false
, allow replacement or elements to be added back in if picked.probs = R_NilValue
, vector containing probability weights
 Examples:
Rounding of Numbers
Ceiling
ceiling( X )  ceil( X ) 

Compute the smallest integer value not less than the corresponding element of X.

Definition: $$\left\lceil X \right\rceil = \min \left[ {n \in \mathbb{Z} n \ge X} \right]$$ 
Supported types are
Numeric
orInteger
of aVector
orMatrix
. 
Note:
ceil
is a mapping toceiling
.  Examples:
floor( X )

Compute the largest integer value not greater than the corresponding element of X.

Definition: $$\left\lfloor X \right\rfloor = \max \left[ {n \in \mathbb{Z} n \le X} \right]$$ 
Supported types are
Numeric
orInteger
of aVector
orMatrix
.  Examples:
trunc( X )

Obtain the integers formed by truncating the values in X toward 0.

Definition:

Supported types are
Numeric
orInteger
of aVector
orMatrix
. 
Examples:
 See also:
round( X , digits )

Obtain a rounded number to specified number of decimal places.

There is no default value for
digits
. This parameter must be specified with anint
. 
Supported types are
Numeric
orInteger
of aVector
orMatrix
. 
Examples:
signif( X, digits )

Round the number to the appropriate number of significant digits.

There is no default value for
digits
. This parameter must be specified with anint
. 
Supported types are
Numeric
orInteger
of aVector
orMatrix
. 
Examples:
Finite, Infinite, Missingness, and NaN Detection

Finite numerical representations take the form of base 10 numbers like 1, 2, …, 42, and so on. These values are able to be operated upon such that a collection of numerical values can provide a statistical summary. However, when working with values that hold special meanings the representation, is not necessarily ideal. Therefore, a set of tools exists to detect when values with special meanings exist.

From Kevin Ushey’s post on StackOverflow, we have a set of truth tables or an indicator of whether the value is detected by a given function, which covers the R interpreter, Rcpp, and R/C API. Note, Rcpp by default follows how R interpreter has crafted the methods.

R interpreter:
Function  NaN 
NA 

is.na 
T 
T 
is.nan 
T 
F 
 Rcpp:
Function  NaN 
NA 

Rcpp::is_na 
T 
T 
Rcpp::is_nan 
T 
F 
 R/C API:
Function  NaN 
NA 

ISNAN 
T 
T 
R_IsNaN 
T 
F 
ISNA 
F 
T 
R_IsNA 
F 
T 
 Note: The R/C API is highly inconsistent when detecting values.
Setting Infinite, Missingness, and NaN Values
 To indicate missingness or
NA
values, the following predefined constants have been made available for specific Rcpp data types:
Rcpp Data Type  Rcpp Value  Description 

Numeric<Vector/Matrix>  NA_REAL 
Numeric Missing Value 
Integer<Vector/Matrix>  NA_INTEGER 
Integer Missing Value 
Logical<Vector/Matrix>  NA_LOGICAL 
Logical Missing Value 
Character<Vector/Matrix>  NA_STRING 
String Missing Value 

To set a missing value type for any type of
Vector
orMatrix
regardless of whether a predefined exists, one can use the static member::get_na()
, e.g.ComplexVector::get_na()
creates anNA
value for a complex vector. 
The
Numeric
anddouble
data types also support the following special constant values:
Rcpp Value  Value  Description 

R_PosInf 
Inf 
Positive Infinity 
R_NegInf 
Inf 
Negative Infinity 
R_NaN 
NaN 
Not a Number 

Note: Understanding the breakdown of the values is important as it relates to detecting whether an element is finite, missing or computationally problematic.

Examples
Finiteness
is_finite( X )  is_infinite( X ) 

Determines whether each element of X are finite (
is_finite
) or infinite (is_infinite
). 
Support exisits for only the
Numeric
type of aVector
orMatrix
. 
Note: Infinite detection is only applicable to
Numeric
types as these values are only defined fordouble
types. 
Caveat: Not a Number is not considered to be a finite nor infinite value. If this value exists within the object, it must be detected with
is_nan
oris_na
. 
Examples:
 See also:
Missing Values and NaN Detection
is_na( X )  is_nan( X ) 

Determines the missing values (
is_na
) or not a number (is_nan
). 
All types are supported of a
Vector
orMatrix
. 
Note: The difference between the two functions is explained by in the truth table
Function  NaN 
NA 

Rcpp::is_na 
T 
T 
Rcpp::is_nan 
T 
F 
 Examples:
na_omit( X )

Removes values that are either
NA
orNaN
. 
All types are supported of a
Vector
orMatrix
. 
Example:
noNA( X )

Assert the object is
NA
free to avoid checking whether each value is not missing. 
All types are supported of a
Vector
orMatrix
. 
Warning: Using
noNA
with aMatrix
defaults the underlying class from aMatrix
toVectorBase
! Thus, the matrix dimensional information is lost. 
Example:
The Apply Family
sapply

Apply a C++ function or functor to each element of an object and receive a
Vector
back. 
The return type is automatically detected by the supplied C++ function or functor of the
Vector
class. 
All types are supported of a
Vector
orMatrix
.
lapply

Apply a C++ function or functor to each element of an object and receive a
List
back. 
All types are supported of a
Vector
orMatrix
.
mapply

Apply a C++ function or functor on up to three input objects and receive a
Vector
. 
The return type is automatically detected by the supplied C++ function or functor of the
Vector
class. 
All types are supported of a
Vector
orMatrix
. 
Example:
 See also:
Special Functions of Mathematics
Beta
beta( A, B )  lbeta( A, B ) 

Compute value of the beta function, $B \left(a,b\right)$, and the natural logarithm of the beta function, $\log \left( {B \left(a,b\right)} \right)$.

Definition:

Supported types are
Integer
orNumeric
of aVector
orMatrix
. 
Examples:
Gamma
gamma( X )  lgamma( X ) 

Compute value of the gamma function, $\Gamma \left(x\right)$, and the natural logarithm of the absolute value of the gamma function, $\log \left( {\left {\Gamma \left( x \right)} \right} \right)$.

Definition:

Supported types are
Integer
orNumeric
of aVector
orMatrix
. 
Examples:
Gamma Derivatives
psigamma( X , deriv )  
digamma( X )  trigamma( X ) 
tetragamma( X )  pentagamma( X ) 

Obtain the n^th^ derivative of the logarithm of the gamma function using
psigamma
. For convenience, derivatives of the second,digamma
, through fifth,pentagamma
, order have been defined. 
Definition:

The
deriv
parameter of thepsigamma
function specifies the derivative to take of the logarithm of the gamma function. 
For the
psigamma
function, only theNumeric
type of theVector
andMatrix
class is supported. The convenience derivative functions have support for bothInteger
andNumeric
type of theVector
andMatrix
class. 
Examples:
Factorials
factorial( X )  lfactorial( X ) 

Compute the product of all positive integers less than or equal to n using
factorial
and the natural logarithm of the absolute value of the factorial withlfactorial
. 
Definition:

Only the
Numeric
type of theVector
andMatrix
class is supported. 
Examples:
Combinatorics
choose( N , K )  lchoose( N , K) 

Compute the binomial coefficients for all real numbers n and integer k using
choose
and the natural logarithm of the absolute value of the binomial coefficients withlchoose
. 
Definition:

Only the
Numeric
type of theVector
andMatrix
class is supported. 
Examples:
Statistical Summaries
Minimum and Maximum
min( X )  max( X ) 

Obtain the extremum value of either a maximum and minimum from within
Vector
orMatrix
. 
Examples:
range( X )

Computes the range or the minimum and maximum values of the sample.

Supported types are
Integer
orNumeric
of aVector
orMatrix
.
mean( X )

Computes the overall sample mean by summing each observation and dividing by the total number of observations.

Definition:

Supported types are
Integer
,Numeric
,Complex
, orLogical
of aVector
orMatrix
.
 See also:
median( X , na_rm)

Computes the sample median by ordering elements from largest to smallest and then selecting the middle element. If an even number of elements is present, then the median consists of an average between the two middle numbers.

All types of a
Vector
orMatrix
are supported. 
Examples:
Variance
var( X )  sd( X ) 

Computes the sample variance and standard deviation formula by taking the corrected sum of squares and dividing it by $N1$.

Definition:

Note: No parameter support exists to switch between population ($\frac{1}{n}$) and sample ($\frac{1}{n1}$) definitions. If necessary, multiple by the multiplication by
double(n1)/n
should provide the appropriate conversion. 
Supported types are
Integer
,Numeric
,Complex
, orLogical
of aVector
orMatrix
.
Special Operations
rev( X )

Reverse the position of the elements within the vector.

All types are supported of a
Vector
orMatrix
. 
Example:
Parallel Extremum
pmax( X, Y )  pmin( X, Y ) 

Obtain a parallel extremum value of either maximum and minimum for either a scalar and a
Vector
or just twoVector
objects. 
For instance, the parallel minimum of X = 0, 1 and Y = 2, 3 would be Z = 0, 3.

Examples:
clamp( min , X , max )

Bound elements of
X
betweenmin
andmax
by replacing the element by the boundary if $X < min$ or $X > max$. 
An alternate version of this function can be obtained with
pmax(min, pmin(X, max) )
. 
Example:
Extremum Indice
which_min( X )  which_max( X ) 

Provides the position in the vector of the minimum or maximum value.

All types are supported of a
Vector
or aMatrix
. 
Examples:
 See also:
Uniqueness Operators
match( X , Y )

Obtain the first locations of a match between elements in X and Y.

All types are supported of a
Vector
or aMatrix
. 
Example:
 See also:
self_match( X )

Obtain the locations of where each element occurs in the object.

All types are supported of a
Vector
or aMatrix
. 
Note: This operation is similar to the R command
match(x, unique(x))
. 
Example:
 See also:
in( X , Y )

Determine whether elements in X are found in Y.

All types are supported of a
Vector
or aMatrix
. 
Example:
 See also:
Unique
duplicated( X )  unique( X ) 

Determine whether duplicates exist within a
Vector
or what the unique values are. 
Duplicated values are identified by a
LogicalVector
such that the first, second, and so on replicates are labeled asTRUE
while unique values areFALSE
. 
Unique provides only the first occurrence of a given value. In essence, only the values that appear as
FALSE
within theduplicate
function. 
Examples:
sort_unique( X )

Determine the unique elements within an object and sort them in increasing order.

All types are supported of a
Vector
or aMatrix
. 
Examples:
table( X )

Given a
Vector
of eitherNumericVector
,IntegerVector
,LogicalVector
, orCharacterVector
, compute anIntegerVector
that contains a count of each value. 
Examples:
Set Operations
setequal(X, Y)

Determine if the values of two objects are equal.

Definition:

All types are supported of a
Vector
orMatrix
. 
Examples:
intersect(X, Y)

Find all elements two objects have in common.

Definition:

All types are supported of a
Vector
orMatrix
. 
Examples:
union_(X, Y)

Obtaining only one copy of all elements that exist in both sets.

Definition:

All types are supported of a
Vector
orMatrix
. 
Note: Union has a postfix of an underscore (
_
) becauseunion
is a keyword in C++. 
Examples:
setdiff(X, Y)

Obtain the elements in A not in B or the intersection of A with the complement of B.

Definition:

All types are supported of a
Vector
orMatrix
. 
Examples:
Matrix Operations
Row and Column Sums
colSums( X , na_rm)  rowSums( X , na_rm ) 

Computes the summation of elements either by column (
colSums
) or row (rowSums
) of aMatrix
. 
Definition:

Supported types are
Numeric
,Integer
orComplex
of theMatrix
class. 
The return type is the equivalent input type but of the
Vector
class. 
Examples:
 See also:
Row and Column Means
colMeans( X , na_rm)  rowMeans( X , na_rm) 

Computes the means of elements either by column (
colMeans
) or row (rowMeans
) of aMatrix
. 
Definition:

Supported types are
Numeric
,Integer
orComplex
of theMatrix
class. 
The return type is the equivalent input type but of the
Vector
class. 
Examples:
 See also:
outer( X , Y , Function)

Applies a
Function
to twoVector
objects to obtain the outer product. 
Definition:

All types of the
Vector
class are supported. However, the suppliedFunction
must have the correct parameter input types to receive values from eachVector
. 
The returned value is a
Matrix
class with its type given by the valued returned by theFunction
.  The
Function
parameter also accepts a C++functor
in place of an RcppFunction
. In such cases, the underlying type T must be defined. Select one of the following arguments for T:int
double
std::complex<double> / Rcomplex
bool
Numeric
Output
Functor  Meaning 

std::plus<T>() 
x + y 
std::minus<T>() 
x  y 
std::multiplies<T>() 
x * y 
std::divides<T>() 
x / y 
std::modulus<T>() 
x % y 
Logical
Output
Functor  Meaning 

std::equal_to<T>() 
x == y 
std::not_equal_to<T>() 
x != y 
std::greater<T>() 
x > y 
std::less<T>() 
x < y 
std::greater_equal<T>() 
x >= y 
std::less_equal<T>() 
x <= y 
 Examples:
 See also:
Triangle Matrix Views
lower_tri( X , diag)  upper_tri( X , diag ) 

Creates a
Matrix
ofLogical
values of the same dimensions as the suppliedMatrix
with values in the lower or upper triangle portion beingtrue
. 
All types are supported of the
Matrix
class. 
By default, the
diag
parameter isfalse
and, therefore, does not include the major diagonal (upper left to lower right). 
Note: Prior to Rcpp 0.13.0, neither the
upper_tri
or thelower_tri
function worked. 
Examples:
diag( X )

Extracts the major diagonal going from the upper left to lower right of a
Matrix
. 
All types of the
Matrix
class are supported. 
The return type is a
Vector
of an equivalent type to the inputMatrix
. 
Example:
Matrix Indexes
col( X )  row( X ) 

Creates a
Matrix
where each element contains either a 1based index for its column (col
) or row (row
). 
All types of the
Matrix
class are supported. 
The return type is an
IntegerMatrix
. 
Examples:
Object Creation
cbind
cbind(X, Y) 
cbind(X, Y, …) 
cbind(X, Y, …)

Creates a
Matrix
by joining objects together in a columnwise manner.  X, Y may be any combination of
Vector
,Matrix
, or atomic value of the same underlying type T, where T is one ofint
double
std::complex<double> / Rcomplex
bool

cbind
is defined for any number of arguments between 2 and 50, inclusive.  Let S1 and S2 be scalar (atomic) values, V be a
Vector
with length k, and M be aMatrix
with with m rows and n columns. Thecbind
function exhibits the following behavior:cbind(S1, S2)
returns a 1 x 2Matrix
.cbind(S1, V)
andcbind(V, S1)
return a k x 2Matrix
, where S1 is recycled k times.cbind(S1, M)
andcbind(M, S1)
return an m x (n + 1)Matrix
, whereS1
is recycled m times. If k and m are equal,
cbind(V, M)
andcbind(M, V)
return an m x nMatrix
.  If k and m are not equal,
cbind(V, M)
andcbind(M, V)
will throw an exception at runtime.  S1 and S2 may be consecutive arguments in a
cbind
expression IFF: they are the only arguments used; or
 all other arguemnts are also scalars; or
 nonscalar, adjacent arguments are vectors of length one, or matrices with one row.
 All other cases involving consecutive arguments S1 and S2 will generate a runtime error.
 Examples:
Sequence Generation
seq_along( X )  seq_len( n ) 

Generate an
Integer
sequence with the index beginning at 1 either based on an object (seq_along
) or length (seq_len
). 
All types are supported of a
Vector
orMatrix
. 
The return type is that of an
IntegerVector
. 
Examples:
Replicate Elements
rep( X, n )  rep_each( X, n )  rep_len( X, n ) 
 Replicate elements in three flavors:
rep
: duplicate the object n times retaining the initial element order.rep_each
: each element is repeated n times consecutively.rep_len
: duplicate object until the new object has length of n.

All types are supported of a
Vector
orMatrix
.  Examples:
String Operations
collapse( X )

Collapse multiple strings values into a single string.

Only the
Character
andString
types of aVector
orMatrix
are supported. 
Note: The function is equivalent to
paste(c('a', 'b'), collapse = "")
. 
Example:
trimws( X, which )

Trim leading and/or trailing whitespace from strings.

The
which
argument controls how the trimming is performed. This is required and can be specified with either"l"
(leading),"r"
(trailing), or"b"
(both). 
Only the
Character
andString
types of aVector
orMatrix
are supported. 
This function provides support for returning either a
String
,Vector
, orMatrix
depending on the supplied parameter. 
Definition: Whitespace in the context of this function is considered to be either: space (
\t
), line feed (\n
), or carriage return (\r
).  Note: The function is equivalent to matching the following
regular expression (regex) patterns:
^[ \t\r\n]+
(left/leading)[ \t\r\n]+$
(right/trailing)^[ \t\r\n]+[ \t\r\n]+$
(both)
 Example:
Statistical Distributions

There exists two approaches for working with statistical distribution functions within Rcpp. The approaches differ on how the result is returned. Specifically, statistical distributions within the
Rcpp::
namespace return typeNumericVector
whereas functions within theR::
namespace return a singledouble
scalar value. 
For drawing large samples with fixed distribution parameters, sampling under one should sample under the
Rcpp::
namespace to obtain aNumericVector
. There is an added benefit to working under this scheme of having default parameters for log probability and lower tail sampling akin to traditional R versions. 
For drawing samples with changing distribution parameters, sampling under the
R::
namespace with afor
loop is perferred as parameters for each draw can be customized.
Discrete Distributions
Binomial Distribution
dbinomial(X, size, prob, log_p) 
pbinomial(Q, size, prob, lower_tail, log_p) 
qbinomial(P, size, prob, lower_tail, log_p) 
rbinomial(n, size, prob) 
Geometric Distribution
dgeom(X, prob, log_p) 
pgeom(Q, prob, lower_tail, log_p) 
qgeom(P, prob, lower_tail, log_p) 
rgeom(n, prob) 
Hypergeometric Distribution
dhyper( X, m, n, k, log_p) 
phyper( Q, m, n, k, lower_tail, log_p) 
qhyper( P, m, n, k, lower_tail, log_p) 
rhyper(nn, m, n, k) 
Negative Binomial Distribution
dnbinomial(X, size, prob, log_p) 
pnbinomial(Q, size, prob, lower_tail, log_p) 
qnbinomial(P, size, prob, lower_tail, log_p) 
rnbinomial(n, size, prob) 
Poisson Distribution
dpois(X, lambda, log_p) 
ppois(Q, lambda, lower_tail, log_p) 
qpois(P, lambda, lower_tail, log_p) 
rpois(n, lambda) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Poisson distribution.

When simulating a vector or scalar from a Poisson distribution, the value returned is within the natural numbers (e.g. $0, 1, 2, \ldots , 42, \ldots , \mathbb{N}$).
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Wilcox Distribution
dwilcox( X, m, n, log_p) 
pwilcox( Q, m, n, lower_tail, log_p) 
qwilcox( P, m, n, lower_tail, log_p) 
rwilcox(nn, m, n) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Wilcox distribution.

When simulating a vector or scalar from a Wilcox distribution, the value returned is within the natural numbers (e.g. $0, 1, 2, \ldots , 42, \ldots , \mathbb{N}$).
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Wilcoxon Signed Rank Distribution
dsignrank( X, n, log_p) 
psignrank( Q, n, lower_tail, log_p) 
qsignrank( P, n, lower_tail, log_p) 
rsignrank(nn, n) 
Continuous Distributions
Beta Distribution
dbeta(X, shape1, shape2, log_p) 
pbeta(Q, shape1, shape2, lower_tail, log_p) 
qbeta(P, shape1, shape2, lower_tail, log_p) 
rbeta(n, shape1, shape2) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Beta distribution.

When simulating a vector or scalar from a Beta distribution, the value returned is within [0, 1].
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Cauchy Distribution
dcauchy(X, location, scale, log_p) 
pcauchy(Q, location, scale, lower_tail, log_p) 
qcauchy(P, location, scale, lower_tail, log_p) 
rcauchy(n, location, scale) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Cauchy distribution.

When simulating a vector or scalar from a Cauchy distribution, the value returned is within (infty, infty).
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Chisquare Distribution
dchisq(X, df, log) 
pchisq(Q, df, lower_tail, log_p) 
qchisq(P, df, lower_tail, log_p) 
rchisq(n, df) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Chisquared distribution.

When simulating a vector or scalar from a Chisquared distribution, the value returned is within [0, infty).
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:log_p = FALSE
, probabilities, densities are returned as log(p).lower_tail = TRUE
, probabilities are calculated by P(X <= x) instead of P(X > x).
 Examples:
Noncentral Chisquare Distribution
dnchisq(X, df, ncp, log_p) 
pnchisq(Q, df, ncp, lower_tail, log_p) 
qnchisq(P, df, ncp, lower_tail, log_p) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Noncentral Chisquared distribution.

When simulating a vector or scalar from a Noncentral Chisquared distribution, the value returned is within $\left[0, \infty\right)$.
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Exponential Distribution
dexp(X, rate, log_p) 
pexp(Q, rate, lower_tail, log_p) 
qexp(P, rate, lower_tail, log_p) 
rexp(n, rate) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from an Exponential distribution under the lambda parameterization: f(v) = lambda x exp(lambda x v)

When simulating a vector or scalar from an Exponential distribution, the value returned is within $\left[0, \infty\right)$.
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:rate = 1
, rate refers to the lambda parameter within an exponentiallog_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
F Distribution
df(X, df1, df2, log_p) 
pf(Q, df1, df2, lower_tail, log_p) 
qf(P, df1, df2, lower_tail, log_p) 
rf(n, df1, df2) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from an F distribution.

When simulating a vector or scalar from an F distribution, the value returned is within [0, infty).
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Noncentral F Distribution
Gamma Distribution
dgamma(X, shape, rate, log_p) 
pgamma(Q, shape, rate, lower_tail, log_p) 
qgamma(P, shape, rate, lower_tail, log_p) 
rgamma(n, shape, rate) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Gamma distribution.

When simulating a vector or scalar from a Gamma distribution, the value returned is within $\left[0, \infty\right)$.
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:rate = 1
,log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Normal Distribution
dnorm(X, mean, sd, log_p) 
pnorm(Q, mean, sd, lower_tail, log_p) 
qnorm(P, mean, sd, lower_tail, log_p) 
rnorm(n, mean, sd) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Normal distribution.

When simulating a vector or scalar from a Normal distribution, the value returned is within $\left(\infty, \infty\right)$.
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:MEAN = 0
, the mean of the distributionSD = 1
, the standard derivation of the distributionlog_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Log Normal Distribution
dlnorm(X, meanlog, sdlog, log_p) 
plnorm(Q, meanlog, sdlog, lower_tail, log_p) 
qlnorm(P, meanlog, sdlog, lower_tail, log_p) 
rlnorm(n, meanlog, sdlog) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Log Normal distribution.

When simulating a vector or scalar from a Log Normal distribution, the value returned is within $\left[0,\infty\right)$.
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:meanlog = 0
, the log mean of the distributionsdlog = 1
, the log standard derivation of the distributionlog_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Logistic Distribution
dlogis(X, location, scale, log_p) 
plogis(Q, location, scale, lower_tail, log_p) 
qlogis(P, location, scale, lower_tail, log_p) 
rlogis(n, location, scale) 

Computes either the density (d), probability (p), quantile (q), or a random (r) sample of a vector or scalar from a Logistic distribution.

When simulating a vector or scalar from a Logistic distribution, the value returned is within $\left(\infty,\infty\right)$.
 Under vectorization, e.g.
Rcpp::
, the default distribution parameters are as follows:location = 0
, the shift component of the distributionscale = 1
, the dispersion parameter of the distribution that changes the spread e.g. if the scale is small, then the distribution is concentrated.log_p = FALSE
, probabilities, densities are returned as $\log(p)$.lower_tail = TRUE
, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$.
 Examples:
Student’s T Distribution
rt()
Uniform Distribution
runif()
Weibull Distribution
rweibull()
Appendix
RTYPES
RTYPE  SEXPTYPE  Description 

0  NILSXP 
NULL 
1  SYMSXP 
symbols 
2  LISTSXP 
pairlists 
3  CLOSXP 
closures 
4  ENVSXP 
environments 
5  PROMSXP 
promises 
6  LANGSXP 
language objects 
7  SPECIALSXP 
special functions 
8  BUILTINSXP 
builtin functions 
9  CHARSXP 
internal character strings 
10  LGLSXP 
logical vectors 
13  INTSXP 
integer vectors 
14  REALSXP 
numeric vectors 
15  CPLXSXP 
complex vectors 
16  STRSXP 
character vectors 
17  DOTSXP 
dotdotdot object 
18  ANYSXP 
make “any” args work 
19  VECSXP 
list (generic vector) 
20  EXPRSXP 
expression vector 
21  BCODESXP 
byte code 
22  EXTPTRSXP 
external pointer 
23  WEAKREFSXP 
weak reference 
24  RAWSXP 
raw vector 
25  S4SXP 
S4 classes not of simple type 
99  FUNSXP 
functions of type CLOSXP , SPECIALSXP and BUILTINSXP 