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 or CMD + 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.

## 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
STL-style Container Functions Standard Library styled functions
Static Member Functions Set of member functions persistant across instances

## Exception Handling

External Exception Classes

stop Stop execution
warning Send Warning to console
Rcout<< Write message to console

Internal Exception Classes

Simple Exceptions

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

Exceptions

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

Logical Operations

ifelse Vectorized If-else
is_false Is Value False?
is_true Is Value True?
any At Least One Value is True
all All Values Must be True

Complex Operators

Re Real Values of Complex Number
Im Imaginary Values of Complex Number
Mod Modulus (r)
Arg Arg (theta)
Conj Complex Conjugate

Data Operations

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

Rounding of Numbers

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

pre-defined Pre-defined 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

The Apply Family

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

Statistical Summaries

min Minimum Value
max Maximum Value
range Range
mean Mean Value
median Median Value
var Variance
sd Standard Deviation

Special Operators

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

Uniqueness Operators

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

Set Operations

setequal Equality of Set Values
intersect Intersection of Set Values
union_ Union of Set Values
setdiff Asymmetric Difference of Set Values

Matrix Operations

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

Object Creation

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$

String Operations

collapse Collapse multiple strings into one string
trimws Trim leading and/or trailing whitespace from strings

Statistical Distributions

Discrete Distributions

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

Continuous Distributions

p/d/q/rbeta Beta
p/d/q/rcauchy Cauchy
p/d/q/rchisq Chi-square
p/d/qnchisq Non-central Chi-square
p/d/q/rexp Exponential
p/d/q/rf F
p/d/qnf Non-central 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 array-like structure providing storage for homogenous data types, with an interface similar to that of std::vector. Being an implementation of policy-based design, much of the behavior of Vector is determined by the policy classes it inherits from

• RObjectMethods
• StoragePolicy
• SlotProxyPolicy
• AttributeProxyPolicy
• NamesProxyPolicy

as well as the CRTP base class VectorBase. This type is instantiated as Vector<RTYPE>, where RTYPE is one of the following valid SEXPTYPEs:

• REALSXP
• INTSXP
• CPLXSXP
• LGLSXP
• STRSXP
• VECSXP
• RAWSXP
• EXPRSXP
• For convenience, the following typedefs have been defined in the Rcpp 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, the Vector object points to the memory location of the SEXP 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, if numeric() data is passed to NumericVector the correct handoff occurs. However, if integer() data were to be passed to a NumericVector a clone() would be made to type numeric() which has its pointer then assigned to the NumericMatrix.

• Examples:

### Matrix

• The main class for matrices is the templated Matrix class, which derives from a combination of both the Vector and MatrixBase types. Like the Vector class, Matrix uses the policy-based design pattern to manage the lifetime of its undelying SEXP via the template parameter StoragePolicy, which uses the PreserveStorage policy class by default. Matrices are
instantiated as Matrix<RTYPE>, where the value RTYPE is one of the following SEXPTYPEs:

• REALSXP
• INTSXP
• CPLXSXP
• LGLSXP
• STRSXP
• VECSXP
• RAWSXP
• EXPRSXP
• For convenience, the following typedefs have been defined in the Rcpp 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, the Vector object points to the memory location of the SEXP 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, if numeric() data is passed to NumericMatrix the correct handoff occurs. However, if integer() data were to be passed to a NumericMatrix a clone() would be made to type numeric() which has its pointer then assigned to the NumericMatrix.

• Examples:

### List

• The List data structure is a typedef of templated Vector class based on the RTYPE of VECSXP that provides heterogenous storage class. As a result, the List class acts as a generic storage object that can simultaneously hold multiple different RTYPE 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, the List constructed from dimensions will have a NULL value set for each element unless a value is otherwise assigned.

• Examples:

### DataFrame

• The DataFrame data structure is a typedef of the DataFrame_Impl class, which is a special extension of the templated Vector class that allows for a collection of heterogenous Vector’s of the same length. As the crux of the implementation of is policy-based design focused, much of the behavior of DataFrame is determined by the policy classes it inherits from

• RObjectMethods
• 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 the RObject_Impl class. Principally, the class can be viewed as the glue of Rcpp due to policy-based design principles. In turn, the RObject class really acts as a “shell” that stores properties of the following policies:

• PreserveStorage: Member functions that provide the SEXP 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, and NULL status.
• Constructors:

- RObject() - RObject(const RObject &other) - RObject(const GenericProxy<Proxy> &proxy)
• Examples:

## Member Functions

### Operators

• Operators allow for operations to take place between two different Vector or Matrix objects. The operations are defined to works in an element-wise fashion where applicable.

• Viable mathematical operations that are able to be performed.

Operation Definition Vector-Vector Vector-Scalar Vector-Matrix 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 Vector-Vector Vector-Scalar Vector-Matrix Matrix - Matrix Matrix - Scalar
== Equality Yes Yes No No Yes
!= Non-equality 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, or R_xlen_t

• Note: As of Rcpp 0.13.0, new size attribute accessors were added to the DataFrame class that mimick those available in Matrix. 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.
• 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 a Matrix with a bounds check.
• (i,j) provides the i,jth element of a Matrix without a bounds check.
• Caveat: Using either [i] or (i) on List and DataFrame, provides the object (e.g. Vector) at position i whereas the use on Vector or Matrix 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 of operator[] relates to a fundamental design choice made by the creators of C++ related to the presence of the operator,. In essence, after the complete evaluation of the first coordinate x and disposal of the results, only then is the second coordinate y able to be evaluated. Unfortunately, this yields the following -Wall issue:

left operand of comma operator has no effect.

Therefore, the only viable matrix subset operators within C++ are operator() and operator at() provide subset operations.

• Examples:

#### Categorical Access

• Access element by name within a Vector, List, or DataFrame.
• (NAME) provides the element associated with the NAME in addition to performing a bounds check that ensures the requested NAME 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, or DataFrame.
• (BOOL) provides only the elements associated true logical condition in addition to performing a bounds check that ensures the requested element at the BOOL location exists.
• [BOOL] similar to the previous case, but does so without a bounds check.
• Caveat: The BOOL must be a LogicalVector of equal size to the object being subset.

• Examples:

### Iterators

• C++ Standard Template Library (STL) styled random access iterators exist underlying the Vector and Matrix 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

### STL-style 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, and list.

• 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, or DataFrame by combining objects together sequentially in a manner similar to c(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 or List, X, Y are allowed to be any combination of Vector, 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:

#### is_na()

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

• Examples:

#### 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:

## Sugar

• The objective behind Rcpp sugar is to provide a subset of the high-level 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 the Matrix is corcered into column-form 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 if-else assignment of elements dependent on the CONDITION being true (TRUEVAL) or false (FALSEVAL).

• To use the vectorized if-else the following criteria must be met:
• CONDITION: A LogicalVector or a sugar expression that evalutes to a LogicalVector
• TRUE/FALSE: either
1. two compatible sugar expression (same RTYPE, same length), OR
2. 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 ) and all( CONDITION ) from the SingleLogicalResult template class to an atomic value bool evaluated as either true or false dependent on whether the call to is_true( X ) or is_false( X ) is matched.

• For example, if any( CONDITION ) evaluates to false than is_true( X ) will return false but is_false( X ) will return true.

• Examples:

#### all( X )

• Tests if all elements in a LogicalVector or LogicalMatrix are true.

• The actual return type of all(X) is an instance of the SingleLogicalResult template class, but the functions is_true and is_false may be used to convert the return value to bool.

• Examples:

#### any( X )

• Tests if any elements in a LogicalVector or LogicalMatrix are true.

• The actual return type of any(X) is an instance of the SingleLogicalResult template class, but the functions is_true and is_false may be used to convert the return value to bool.

• Examples:

### Complex Operators

#### Complex Components

Re( X ) Im( X )
• Extract the real or imaginary component of a complex number.

• Definition: $z = x + i y$, where $x, y \in \mathbb{R}$.

• X must be stored within a Vector or Matrix of type Complex. The return type is a NumericVector regardless of whether a Vector or Matrix is supplied.

• Example:

#### 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: $r = \operatorname{Mod}(z) = \sqrt{x^2 + y^2}$

• X must be stored within a Vector or Matrix of type Complex. The return type is a NumericVector regardless of whether a Vector or Matrix is supplied.

• Example:

#### 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: $\theta = \arctan\left({\frac{y}{x} }\right)$

• X must be stored within a Vector or Matrix of type Complex. The return type is a NumericVector regardless of whether a Vector or Matrix is supplied.

• Example:

#### 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 or Matrix of type Complex. The return type is a ComplexVector regardless of whether a Vector or Matrix is supplied.

• Example:

### Data Operations

#### First or Last Elements

head( X , n ) tail( X , n )
• Obtain the first or last n observations using head or tail.

• All types of a Vector or Matrix are supported.

• Example:

#### abs( X )

• Obtain the absolute value of all elements.

• Definition: $% $

• Supported types to perform the operation are Numeric or Integer of a Vector or Matrix.

• Example:

#### sqrt( X )

• Compute the square root of all elements.

• Definition: $\sqrt{X} = X^{1/2}$

• Supported types to perform the operation are Numeric, Integer, or Complex of a Vector or Matrix.

• Example:

#### pow( X , n)

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

• Definition: $Y = X^{n}$

• Supported types to perform the operation are Numeric or Integer of a Vector or Matrix.

• Caveat: Only X is able to be vectorized. The value of n must be a scalar of int or double type.

• Example:

#### sum( X )

• Calculate the overall summation of all elements.

• Definition: $Y = \sum\limits_{i = 1}^n { {X_i} }$

• Supported types to perform the operation are Numeric or Integer of a Vector or Matrix.

• Example:

#### sign( X )

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

• Definition: $% 0 \end{cases} %]]>$

• Supported types are Numeric or Integer of a Vector or Matrix.

• Example:

#### diff( X )

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

• Definition: $\nabla {X_i} = {X_{i + 1} } - {X_i}$

• Supported types are Numeric or Integer of a Vector or Matrix.

• Example:

#### Cumulative Arithmetic

cumsum( X ) cumprod( X )
• Calculates the cumulative sum (cumsum) or cumulative product (cumprod) of a Vector or Matrix X.

• If an NA value is encountered, it will be propagated throughout the remaining elements in the result vector.

• For cumsum, X should be an Integer or Numeric Vector or Matrix.

• For cumprod, X should be an Integer, Numeric, or Complex Vector or Matrix.

• In either case, the return type is a Vector of the same underlying SEXPTYPE 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 a Vector. 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 target Vector; or
• Calling an explicit conversion member function of the Sugar class, if such a function exists.

See the examples below for a demonstration.

• Examples:

#### Cumulative Extremum

cummax( X ) cummin( X )
• Calculates the cumulative maximum (cummax) or cumulative minimum (cummin) of a Vector or Matrix X.

• If an NA value is encountered, it will be propagated throughout the remaining elements in the result vector.

• Supported types are Integer or Numeric of a Vector or Matrix.

• 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 a Vector. 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 target Vector; or
• Calling an explicit conversion member function of the Sugar class, if such a function exists.

See the examples below for a demonstration.

• Examples:

#### trigonometric element-wise 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 and Y must be of the same vector_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)
• Supported types are Integer, Numeric, or Complex of a Vector or Matrix.

• 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 and Y must be of the same vector_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: $\exp \left( X \right) = \mathop {\lim }\limits_{n \to \infty } {\left( {1 + \frac{X}{n} } \right)^n} = \sum\limits_{k = 0}^\infty {\frac{ { {X^k} } }{ {k!} } }$
• Special use cases:
•  log1p( X ) computes $\log( 1 + X )$ accurately for $\left X\right « 1$.
•  expm1( X ) computes $\exp( X ) - 1$ accurately for $\left X\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 or Matrix.

• The parameters available for sample are defined as:
• size, the number of items to sample
• replace = 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 or Integer of a Vector or Matrix.

• Note: ceil is a mapping to ceiling.

• 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 or Integer of a Vector or Matrix.

• Examples:

#### trunc( X )

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

• Definition: $% 0 \\ \left\lceil X \right\rceil, &\text{if} X < 0 \end{cases} %]]>$

• Supported types are Numeric or Integer of a Vector or Matrix.

• Examples:

#### 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 an int.

• Supported types are Numeric or Integer of a Vector or Matrix.

• 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 an int.

• Supported types are Numeric or Integer of a Vector or Matrix.

• 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 pre-defined 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 or Matrix regardless of whether a pre-defined exists, one can use the static member ::get_na(), e.g. ComplexVector::get_na() creates an NA value for a complex vector.

• The Numeric and double 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

#### 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 a Vector or Matrix.

• Note: Infinite detection is only applicable to Numeric types as these values are only defined for double 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 or is_na.

• Examples:

#### 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 or Matrix.

• 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 or NaN.

• All types are supported of a Vector or Matrix.

• 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 or Matrix.

• Warning: Using noNA with a Matrix defaults the underlying class from a Matrix to VectorBase! 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 or Matrix.

#### 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 or Matrix.

#### 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 or Matrix.

• Example:

### 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 or Numeric of a Vector or Matrix.

• 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 or Numeric of a Vector or Matrix.

• 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 the psigamma function specifies the derivative to take of the logarithm of the gamma function.

• For the psigamma function, only the Numeric type of the Vector and Matrix class is supported. The convenience derivative functions have support for both Integer and Numeric type of the Vector and Matrix 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 with lfactorial.

• Definition: % 0 \end{cases} \\ &= \Gamma\left(n+1\right) \\ \log \left( {\left| {n!} \right|} \right) &= \log \left( {\left| {\Gamma \left( {n + 1} \right)} \right|} \right) \end{aligned} %]]>

• Only the Numeric type of the Vector and Matrix 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 with lchoose.

• Definition: %

• Only the Numeric type of the Vector and Matrix 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 or Matrix.

• Examples:

#### range( X )

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

• Supported types are Integer or Numeric of a Vector or Matrix.

#### mean( X )

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

• Definition: $\bar{X} = \frac{1}{n}\sum\limits_{i = 1}^n { {X_i} }$

• Supported types are Integer, Numeric, Complex, or Logical of a Vector or Matrix.

#### 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 or Matrix 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 $N-1$.

• Definition: %

• Note: No parameter support exists to switch between population ($\frac{1}{n}$) and sample ($\frac{1}{n-1}$) definitions. If necessary, multiple by the multiplication by double(n-1)/n should provide the appropriate conversion.

• Supported types are Integer, Numeric, Complex, or Logical of a Vector or Matrix.

### Special Operations

#### rev( X )

• Reverse the position of the elements within the vector.

• All types are supported of a Vector or Matrix.

• 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 two Vector 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 between min and max 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 a Matrix.

• Examples:

### 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 a Matrix.

• Example:

#### self_match( X )

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

• All types are supported of a Vector or a Matrix.

• Note: This operation is similar to the R command match(x, unique(x)).

• Example:

#### in( X , Y )

• Determine whether elements in X are found in Y.

• All types are supported of a Vector or a Matrix.

• Example:

#### 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 as TRUE while unique values are FALSE.

• Unique provides only the first occurrence of a given value. In essence, only the values that appear as FALSE within the duplicate 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 a Matrix.

• Examples:

### table( X )

• Given a Vector of either NumericVector, IntegerVector, LogicalVector, or CharacterVector, compute an IntegerVector that contains a count of each value.

• Examples:

### Set Operations

#### setequal(X, Y)

• Determine if the values of two objects are equal.

• Definition: $A = B = \left\{ {\forall x:x \in A \wedge x \in B} \right\}$

• All types are supported of a Vector or Matrix.

• Examples:

#### intersect(X, Y)

• Find all elements two objects have in common.

• Definition: $A \cap B = \left\{ {x:x \in A \wedge x \in B} \right\}$

• All types are supported of a Vector or Matrix.

• Examples:

#### union_(X, Y)

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

• Definition: $A \cup B = \left\{ {x:x \in A \vee x \in B} \right\}$

• All types are supported of a Vector or Matrix.

• Note: Union has a postfix of an underscore (_) because union 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: $A\backslash B = A - B = A \cap {B^C} = \left\{ {x:x \in A \wedge x \notin B} \right\}$

• All types are supported of a Vector or Matrix.

• 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 a Matrix.

• Definition:

• Supported types are Numeric, Integer or Complex of the Matrix class.

• The return type is the equivalent input type but of the Vector class.

• Examples:

#### 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 a Matrix.

• Definition:

• Supported types are Numeric, Integer or Complex of the Matrix class.

• The return type is the equivalent input type but of the Vector class.

• Examples:

#### outer( X , Y , Function)

• Applies a Function to two Vector objects to obtain the outer product.

• Definition: %

• All types of the Vector class are supported. However, the supplied Function must have the correct parameter input types to receive values from each Vector.

• The returned value is a Matrix class with its type given by the valued returned by the Function.

• The Function parameter also accepts a C++ functor in place of an Rcpp Function. 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:

#### Triangle Matrix Views

lower_tri( X , diag) upper_tri( X , diag )
• Creates a Matrix of Logical values of the same dimensions as the supplied Matrix with values in the lower or upper triangle portion being true.

• All types are supported of the Matrix class.

• By default, the diag parameter is false 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 the lower_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 input Matrix.

• Example:

#### Matrix Indexes

col( X ) row( X )
• Creates a Matrix where each element contains either a 1-based 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 column-wise manner.

• X, Y may be any combination of Vector, Matrix, or atomic value of the same underlying type T, where T is one of
• int
• 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 a Matrix with with m rows and n columns. The cbind function exhibits the following behavior:
• cbind(S1, S2) returns a 1 x 2 Matrix.
• cbind(S1, V) and cbind(V, S1) return a k x 2 Matrix, where S1 is recycled k times.
• cbind(S1, M) and cbind(M, S1) return an m x (n + 1) Matrix, where S1 is recycled m times.
• If k and m are equal, cbind(V, M) and cbind(M, V) return an m x n Matrix.
• If k and m are not equal, cbind(V, M) and cbind(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
• non-scalar, 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 or Matrix.

• 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 or Matrix.

• Examples:

### String Operations

#### collapse( X )

• Collapse multiple strings values into a single string.

• Only the Character and String types of a Vector or Matrix 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 and String types of a Vector or Matrix are supported.

• This function provides support for returning either a String, Vector, or Matrix depending on the supplied parameter.

• Definition: Whitespace in the context of this function is considered to be either: space ( ), horizontal tab (\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 type NumericVector whereas functions within the R:: namespace return a single double scalar value.

• For drawing large samples with fixed distribution parameters, sampling under one should sample under the Rcpp:: namespace to obtain a NumericVector. 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 a for 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:

#### Chi-square 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 Chi-squared distribution.

• When simulating a vector or scalar from a Chi-squared 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:

#### Non-central Chi-square 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 Non-central Chi-squared distribution.

• When simulating a vector or scalar from a Non-central Chi-squared 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 exponential
• 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:

#### 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:

#### 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 distribution
• SD = 1, the standard derivation of the distribution
• 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:

### 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 distribution
• sdlog = 1, the log standard derivation of the distribution
• 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:

### 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 distribution
• scale = 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:

rt()

runif()

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 dot-dot-dot 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