├── .gitignore ├── rcpp-api.Rproj ├── README.md └── rcpp-api-docs.Rmd /.gitignore: -------------------------------------------------------------------------------- 1 | .Rproj.user 2 | .Rhistory 3 | .RData 4 | .Ruserdata 5 | *.html 6 | *.pdf 7 | -------------------------------------------------------------------------------- /rcpp-api.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 4 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rcpp API Documentation (`rcpp-api`) 2 | 3 | This repository contains the Rcpp API documentation project. The project is 4 | rooted in providing a much needed face lift to working with one of the most 5 | popular ways to augment _R_ with _C++_. 6 | 7 | ## Goal 8 | 9 | Provide documentation that lists, describes, and provides an example of each 10 | known Rcpp data type and function alongside best practices. The documentation 11 | should be ready for inclusion within Rcpp 1.x.0 scheduled for release in 12 | January 2018. 13 | 14 | ## Style 15 | 16 | The main style for this documentation will mimic the [Armadillo documentation](http://arma.sourceforge.net/docs.html) 17 | that involves first listing the different data structures before detailing class 18 | methods and overall function uses. 19 | 20 | Each section should contain: 21 | 22 | - Name of data type or function 23 | - Comment as to what arguments are accepted 24 | - Notes related to any limitations or C++ specific difference (e.g. 20 parameters for `::create()`) 25 | - Examples that are written as if they are embedded within a function or main 26 | alongside their expected output in comment form 27 | - Vectors or matrices should be written in _uppercase_ and 28 | follow a logical alphabetic naming progression (e.g. `A`, `B = 2*A`) 29 | - Scalar should be written in _lowercase_ (e.g. `summed`, `val_summed`) 30 | 31 | The following sample echoes the above tenets 32 | 33 | ```` 34 | ``` 35 | ### sum( X ) {#sum} 36 | 37 | - Compute the overall summation of all elements. 38 | 39 | - Supported types are `Numeric`, `Integer`, or `Logical` in a `Vector` or `Matrix`. 40 | 41 | - Examples: 42 | 43 | ```cpp 44 | // Sample data 45 | NumericVector X = NumericVector::create(3.2, 8.1, 9.5, 8.6, 5.7); 46 | 47 | double val_sum = sum(X); 48 | // Output: 35.1 49 | ``` 50 | 51 | - See also: 52 | - [rowSums](#rowSums) 53 | - [colSums](#colSums) 54 | ```` 55 | 56 | Functions that share common features such as the trigonometric and probability 57 | distribution functions should be grouped together under a common banner to 58 | decrease repeative entries. The name of the entry should be `[subject](#subject-ref-tag)` 59 | to allow for "See also" links and inclusion in the Table of Contents. 60 | 61 | ## Contributing 62 | 63 | To contribute, please submit a [Pull Request (PR)](https://github.com/coatless/rcpp-api/pulls) 64 | with the desired documentation change. -------------------------------------------------------------------------------- /rcpp-api-docs.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Unofficial Rcpp API Documentation" 3 | output: 4 | pdf_document: default 5 | html_document: default 6 | date: '`r format(Sys.time(), "%F %T %z")`' 7 | --- 8 | 9 | ```{r setup, include=FALSE} 10 | knitr::opts_chunk$set(echo = TRUE, eval = FALSE) 11 | ``` 12 | 13 | **Warning: This post is a work in progress. It will periodically be updated 14 | as time permits.** 15 | 16 | # Introduction 17 | 18 | The following **unofficial** API documentation for [Rcpp](http://rcpp.org) is based off some 19 | personal notes and teaching materials that I have prepared over the years of 20 | working with Rcpp. I've attempted to reformat the notes in the form of [Armadillo's API](http://arma.sourceforge.net/docs.html), 21 | which I think are some of the best documentation out there for a C++ matrix library. 22 | At some point, when the documentation becomes a bit more stable or if there is 23 | larger contributor interest, I will likely attempt to merge this into the Rcpp 24 | project so that a docs subdomain could hopefully be added to . 25 | 26 | Please note: The post is written using [RMarkdown](http://rmarkdown.rstudio.com) 27 | for maximum flexibility. 28 | 29 | # API Documentation for Rcpp 0.12.11 30 | 31 | ## Preamble 32 | 33 | - The goal of the API documentations are to provide a public facing concise 34 | view of Rcpp features. As a result, the documentation will be somewhat long. 35 | To help navigate the documentation, it has been split into different sections. 36 | Furthermore, one should use the built in search functionality to search text 37 | for keywords using either `CTRL` + `F` on Windows and Linux or `CMD` + `F` on 38 | macOS. 39 | 40 | - Presently, any contribution to this document can be made by a [pull request 41 | (PRs)](https://github.com/coatless/rcpp-api/pulls) on GitHub. 42 | 43 | - Please report any bugs to the [Rcpp Core Team](https://github.com/rcppcore/rcpp/issues). 44 | 45 | ## Overview 46 | 47 | - [Vector, Matrix, List, DataFrame](#vmld) 48 | - [Member functions](#member-functions) 49 | - [Operators](#ops) 50 | - [Dimensional Information](#dim-info) 51 | - [Element Access](#elem-access) 52 | - [Position Access](#position-access) 53 | - [Categorical Access](#categorical-access) 54 | - [Logical Access](#logical-access) 55 | - [Subset Views](#subview) 56 | - [Iterators](#iterators) 57 | - [STL-style container functions](#stl-functions) 58 | - [Static Member Functions](#static-members) 59 | - [Sugar](#sugar) 60 | - [Statistical Distributions](#stat-dist) 61 | - [Exception Handling](#exception-handling) 62 | - [External Exception Classes](#external-exception-clasess) 63 | - [Internal Exception Classes](#internal-exception-clasess) 64 | - [Simple Exceptions](#simple-exception) 65 | - [Exceptions](#exception) 66 | - [Advanced exceptions](#advanced-exception) 67 | - Environment, Function, Language 68 | - XPtr 69 | - S4 classes / modules 70 | 71 | ------ 72 | 73 | ## Vector, Matrix, List, and DataFrame Classes 74 | 75 | | | | 76 | |:----------------------------------------------------------------|:-------------------| 77 | | [Vector<*RTYPE*>, NumericVector, IntegerVector, ...](#vector) | Vector class | 78 | | [Matrix<*RTYPE*>, NumericMatrix, IntegerMatrix, ...](#matrix) | Matrix class | 79 | | [List](#list) | List typedef | 80 | | [DataFrame](#dataframe) | Data frame class | 81 | | [RObject](#robject) | RObject class | 82 | 83 | ## Member functions 84 | 85 | | | | 86 | |:-------------------------------------------------|:-------------------------------------------------------------------| 87 | | [Operators](#ops) | Mathematical (add, subtract, etc) and logical (inequalities) | 88 | | [Dimensional Information](#dim-info) | Size attribute information | 89 | | [Element Access](#elem-access) | Retrieving element values with and without bounds check | 90 | | [Subset Views](#subview) | Subset data structures | 91 | | [Iterators](#iterators) | Random access iterators | 92 | | [STL-style Container Functions](#stl-functions) | Standard Library styled functions | 93 | | [Static Member Functions](#static-members) | Set of member functions persistant across instances | 94 | 95 | ## Exception Handling 96 | 97 | **[External Exception Classes](#external-exception-clasess)** 98 | 99 | | | | 100 | |------------------------------------|------------------------------| 101 | | [`stop`](#stop) | Stop execution | 102 | | [`warning`](#warning) | Send Warning to console | 103 | 104 | **[Internal Exception Classes](#internal-exception-clasess)** 105 | 106 | _[Simple Exceptions](#simple-exception)_ 107 | 108 | | | | 109 | |-----------------------------------------------|--------------------------------| 110 | | [`not_a_matrix`](#simple-exception) | Object is not a matrix | 111 | | [`parse_error`](#simple-exception) | Unable to parse values | 112 | | [`not_s4`](#simple-exception) | Not a valid S4 class | 113 | | [`not_reference`](#simple-exception) | Object not a reference | 114 | | [`not_initialized`](#simple-exception) | Object not initialized | 115 | | [`no_such_slot`](#simple-exception) | S4 Object lacks slot | 116 | | [`no_such_field`](#simple-exception) | Exception not used | 117 | | [`not_a_closure`](#simple-exception) | Object not a closure | 118 | | [`no_such_function`](#simple-exception) | No such function | 119 | | [`unevaluated_promise`](#simple-exception) | Promise not yet evaluated | 120 | 121 | 122 | _[Exceptions](#exception)_ 123 | 124 | | | | 125 | |-----------------------------------------------|-----------------------------------| 126 | | [`S4_creation_error`](#exception) | Error creating object of S4 class | 127 | | [`reference_creation_error`](#exception) | Exception not used | 128 | | [`no_such_binding`](#exception) | No such binding | 129 | | [`binding_not_found`](#exception) | Binding not found | 130 | | [`binding_is_locked`](#exception) | Binding is locked | 131 | | [`no_such_namespace`](#exception) | No such namespace | 132 | | [`function_not_exported`](#exception) | Function not exported | 133 | | [`eval_error`](#exception) | Evaluation error | 134 | 135 | 136 | _[Advanced exceptions](#advanced-exception)_ 137 | 138 | | | | 139 | |-----------------------------------------------|---------------------------------| 140 | | [`not_compatible`](#adv-exception) | Not a compatible transformation | 141 | | [`index_out_of_bounds`](#adv-exception) | Request index is out of bounds | 142 | 143 | 144 | ## Sugar 145 | 146 | **[Logical Operations](#sugar-logic-ops)** 147 | 148 | | | | 149 | |:-----------------------------|:---------------------------| 150 | | [`ifelse`](#ifelse) | Vectorized If-else | 151 | | [`is_false`](#isbool) | Is Value False? | 152 | | [`is_true`](#isbool) | Is Value True? | 153 | | [`any`](#any) | At Least One Value is True | 154 | | [`all`](#all) | All Values Must be True | 155 | 156 | **[Complex Operators](#sugar-complex-ops)** 157 | 158 | | | | 159 | |:------------------------------|:-----------------------------------| 160 | | [`Re`](#complex-number) | Real Values of Complex Number | 161 | | [`Im`](#complex-number) | Imaginary Values of Complex Number | 162 | | [`Mod`](#complex-modulus) | Modulus (r) | 163 | | [`Arg`](#complex-arg) | Arg (theta) | 164 | | [`Conj`](#complex-conjugate) | Complex Conjugate | 165 | 166 | **[Data Operations](#sugar-data-ops)** 167 | 168 | | | | 169 | |:----------------------------|:------------------------------| 170 | | [`head`](#first-last-elems) | View the First _n_ Values | 171 | | [`tail`](#first-last-elems) | View the Last _n_ Values | 172 | | [`abs`](#abs) | Absolute Value | 173 | | [`sqrt`](#sqrt) | Square Root | 174 | | [`pow`](#pow) | Raise to the _n_^th^ Power | 175 | | [`sum`](#sum) | Summation | 176 | | [`sign`](#sign) | Extract the Sign of Values | 177 | | [`diff`](#diff) | Lagged Difference | 178 | | [`cumsum`](#carth) | Cumulative Sum | 179 | | [`cumprod`](#carth) | Cumulative Product | 180 | | [`cummin`](#cext) | Cumulative Minimum | 181 | | [`cummax`](#cext) | Cumulative Maximum | 182 | | [`sin`](#trig) | Sine | 183 | | [`cos`](#trig) | Cosine | 184 | | [`tan`](#trig) | Tangent | 185 | | [`asin`](#trig) | Arc Sine | 186 | | [`acos`](#trig) | Arc Cosine | 187 | | [`atan`](#trig) | Arc Tangent | 188 | | [`sinh`](#trig) | Hyperbolic Sine | 189 | | [`cosh`](#trig) | Hyperbolic Cosine | 190 | | [`tanh`](#trig) | Hyperbolic Tangent | 191 | | [`log`](#logexp) | Natural Logarithms | 192 | | [`exp`](#logexp) | Expoential | 193 | | [`log10`](#logexp) | Base 10 Logarithm | 194 | | [`log1p`](#logexp) | Natural Logarithm $log(1+x)$ | 195 | | [`expm1`](#logexp) | $\exp(x) - 1$ | 196 | | [`sample`](#sample) | Randomly sample values | 197 | 198 | **[Rounding of Numbers](#sugar-rounding)** 199 | 200 | | | | 201 | |:-----------------------------------|:----------------------------------------------| 202 | | [`ceiling`](#ceil),[`ceil`](#ceil) | Smallest integer greater than or equal to x | 203 | | [`trunc`](#trunc) | Truncates the values in x toward 0 | 204 | | [`floor`](#floor) | Largest integer less than or equal to x | 205 | | [`round`](#round) | Round values to specified decimal place | 206 | | [`signif`](#signif) | Rounds values to number of significant digits | 207 | 208 | 209 | **[Finite, Infinite and NaN Detection](#sugar-nan)** 210 | 211 | | | | 212 | |:-----------------------------------|:-------------------------------------------| 213 | | [`pre-defined`](#nanconstants) | Pre-defined NA/NaN/Inf Constants | 214 | | [`is_na`](#missingness) | Detects if values are missing | 215 | | [`is_nan`](#missingness) | Detects if values are not a number (`NaN`) | 216 | | [`is_finite`](#finite) | Detects if value is finite | 217 | | [`is_infinite`](#finite) | Detects if value is infinite | 218 | | [`na_omit`](#na-omit) | Remove `NA` and `NaN` values | 219 | | [`noNA`](#nona) | Assert that the object is `NA` free | 220 | 221 | 222 | **[The Apply Family](#sugar-apply)** 223 | 224 | | | | 225 | |:----------------------|:----------------------------------------------------------------| 226 | | [`sapply`](#sapply) | Apply a function to one input and store results in vector | 227 | | [`lapply`](#lapply) | Apply a function to one input and store results in list | 228 | | [`mapply`](#mapply) | Apply a function to multiple inputs and store results in vector | 229 | 230 | **[Special Functions of Mathematics](#sugar-special-math)** 231 | 232 | | | | 233 | |:-----------------------------|:---------------------------| 234 | | [`factorial`](#factorials) | Factorial | 235 | | [`lfactorial`](#factorials) | Factorial Logarithm | 236 | | [`choose`](#combinatorics) | Combination | 237 | | [`lchoose`](#combinatorics) | Combination Logarithm | 238 | | [`beta`](#beta) | Beta Function | 239 | | [`lbeta`](#beta) | Natural Log Beta Function | 240 | | [`gamma`](#gamma) | Gamma Function | 241 | | [`lgamma`](#gamma) | Natural Log Gamma Function | 242 | | [`psigamma`](#gamma-deriv) | General Gamma Derivative | 243 | | [`digamma`](#gamma-deriv) | Second Gamma Derivative | 244 | | [`trigamma`](#gamma-deriv) | Third Gamma Derivative | 245 | | [`tetragamma`](#gamma-deriv) | Fourth Gamma Derivative | 246 | | [`pentagamma`](#gamma-deriv) | Fifth Gamma Derivative | 247 | 248 | **[Statistical Summaries](#sugar-stats)** 249 | 250 | | | | 251 | |:---------------------|:---------------------| 252 | | [`min`](#minmax) | Minimum Value | 253 | | [`max`](#minmax) | Maximum Value | 254 | | [`range`](#range) | Range | 255 | | [`mean`](#mean) | Mean Value | 256 | | [`median`](#median) | Median Value | 257 | | [`var`](#var) | Variance | 258 | | [`sd`](#var) | Standard Deviation | 259 | 260 | **[Special Operators](#sugar-special-ops)** 261 | 262 | | | | 263 | |:-----------------------|:-------------------------------------| 264 | | [`rev`](#rev) | Reverse ordering of a vector | 265 | | [`pmax`](#pext) | Parallel maximum value | 266 | | [`pmin`](#pext) | Parallel minimum value | 267 | | [`clamp`](#clamp) | Values between a minimum and maximum | 268 | | [`which_max`](#which) | Index of the maximum value | 269 | | [`which_min`](#which) | Index of the minimum value | 270 | 271 | 272 | **[Uniqueness Operators](#sugar-unique-ops)** 273 | 274 | | | | 275 | |:------------------------------|:---------------------------------------------------------------| 276 | | [`match`](#match) | Find indices of the first value in a separate vector | 277 | | [`self_match`](#self-match) | Find indices of the first occurrence of each value in a vector | 278 | | [`in`](#in) | Determine if a match was located for each element of _A_ in _B_| 279 | | [`unique`](#unique) | Obtain the unique values | 280 | | [`duplicated`](#unique) | Obtain a logical vector indicating the duplicate values | 281 | | [`sort_unique`](#sort-unique) | Obtain the unique values and sort them | 282 | | [`table`](#table) | Create a frequency table of occurrences | 283 | 284 | 285 | **[Set Operations](#sugar-set-ops)** 286 | 287 | | | | 288 | |:--------------------------|:-----------------------------------------| 289 | | [`setequal`](#setequal) | Equality of Set Values | 290 | | [`intersect`](#intersect) | Intersection of Set Values | 291 | | [`union_`](#union) | Union of Set Values | 292 | | [`setdiff`](#setdiff) | Asymmetric Difference of Set Values | 293 | 294 | 295 | **[Matrix Operations](#sugar-matrix-ops)** 296 | 297 | | | | 298 | |:---------------------------|:-----------------------------------------------| 299 | | [`colSums`](#matrix-sum) | Column Sums of a Matrix | 300 | | [`rowSums`](#matrix-sum) | Row Sums of a Matrix | 301 | | [`colMeans`](#matrix-mean) | Column Means of a Matrix | 302 | | [`rowMeans`](#matrix-mean) | Row Means of a Matrix | 303 | | [`outer`](#outer) | Outer Product of Arrays on a Function | 304 | | [`lower_tri`](#tri-mat) | Extract the _Lower_ Triangle Part of a Matrix | 305 | | [`upper_tri`](#tri-mat) | Extract the _Upper_ Triangle Part of a Matrix | 306 | | [`diag`](#diag) | Extract the Diagonal Portion of a Matrix | 307 | | [`row`](#idx-mat) | Create a matrix of Row Indexes | 308 | | [`col`](#idx-mat) | Create a matrix of Column Indexes | 309 | 310 | 311 | **[Object Creation](#sugar-object-creation)** 312 | 313 | | | | 314 | |:--------------------|:-----------------------------------------------| 315 | | [`cbind`](#cbind) | Create matrix by combing column vectors | 316 | | [`seq_along`](#seq) | Generate an R index sequence given a vector | 317 | | [`seq_len`](#seq) | Generate an R index sequence given an integer | 318 | | [`rep`](#rep) | Replicate vector $N$ times | 319 | | [`rep_each`](#rep) | Replicate each element in line $N$ times | 320 | | [`rep_len`](#rep) | Replicate values until vector is of length $N$ | 321 | 322 | **[String Operations](#sugar-string-ops)** 323 | 324 | | | | 325 | |:------------------------|:-----------------------------------------------------| 326 | | [`collapse`](#collapse) | Collapse multiple strings into one string | 327 | | [`trimws`](#trimws) | Trim leading and/or trailing whitespace from strings | 328 | 329 | 330 | 331 | **[Statistical Distributions](#stat-dist)** 332 | 333 | **[Discrete Distributions](#discrete-dist)** 334 | 335 | | | | 336 | |-----------------------------------|------------------------| 337 | | [`p/d/q/rbinom`](#bin-dist) | Binomial | 338 | | [`p/d/q/rgeom`](#geo-dist) | Geometric | 339 | | [`p/d/q/rhyper`](#hypergeo-dist) | Hypergeometric | 340 | | [`p/d/q/rnbinom`](#negbin-dist) | Negative Binomial | 341 | | [`p/d/q/rpois`](#pois-dist) | Poisson | 342 | | [`p/d/q/rwilcox`](#wilcox-dist) | Wilcoxon | 343 | | [`p/d/q/rsignrank`](#signed-dist)| Wilcoxon Signed Rank | 344 | 345 | **[Continuous Distributions](#continuous-dist)** 346 | 347 | | | | 348 | |------------------------------------|------------------------------| 349 | | [`p/d/q/rbeta`](#beta-dist) | Beta | 350 | | [`p/d/q/rcauchy`](#cauchy-dist) | Cauchy | 351 | | [`p/d/q/rchisq`](#chisquare-dist) | Chi-square | 352 | | [`p/d/qnchisq`](#nchisquare-dist) | Non-central Chi-square | 353 | | [`p/d/q/rexp`](#exp-dist) | Exponential | 354 | | [`p/d/q/rf`](#f-dist) | F | 355 | | [`p/d/qnf`](#nf-dist) | Non-central F | 356 | | [`p/d/q/rgamma`](#gamma-dist) | Gamma | 357 | | [`p/d/q/rnorm`](#normal-dist) | Normal | 358 | | [`p/d/q/rlnorm`](#lognormal-dist) | Log Normal | 359 | | [`p/d/q/rlogis`](#logistic-dist) | Logistic | 360 | | [`p/d/q/rt`](#t-dist) | Student's T | 361 | | [`p/d/q/runif`](#unif-dist) | Uniform | 362 | | [`p/d/q/rweibull`](#weibull-dist) | Weibull | 363 | 364 | ## Vector, Matrix, List, and DataFrame Classes {#vmld} 365 | 366 | ### Vector {#vector} 367 | 368 | - The templated `Vector` class is a one dimensional array-like structure 369 | providing storage for homogenous data types, with an 370 | interface similar to that of `std::vector`. Being an implementation of 371 | [policy-based design](https://en.wikipedia.org/wiki/Policy-based_design), 372 | much of the behavior of `Vector` is determined by the policy classes it 373 | inherits from 374 | 375 | - `RObjectMethods` 376 | - `StoragePolicy` 377 | - `SlotProxyPolicy` 378 | - `AttributeProxyPolicy` 379 | - `NamesProxyPolicy` 380 | 381 | as well as the CRTP base class `VectorBase`. This type is instantiated as 382 | `Vector`, where `RTYPE` is one of the following valid `SEXPTYPE`s: 383 | 384 | - `REALSXP` 385 | - `INTSXP` 386 | - `CPLXSXP` 387 | - `LGLSXP` 388 | - `STRSXP` 389 | - `VECSXP` 390 | - `RAWSXP` 391 | - `EXPRSXP` 392 | 393 | - For convenience, the following [`typedefs` have been defined](https://github.com/RcppCore/Rcpp/blob/6f81b4684481dbd9bb554dd95e66725fc3b63a8c/inst/include/Rcpp/vector/instantiation.h#L27-L38) in the `Rcpp` namespace: 394 | 395 | - `NumericVector` = `Vector` 396 | - `DoubleVector` = `Vector` 397 | - `RawVector` = `Vector` 398 | - `IntegerVector` = `Vector` 399 | - `ComplexVector` = `Vector` 400 | - `LogicalVector` = `Vector` 401 | - `CharacterVector` = `Vector` 402 | - `StringVector` = `Vector` 403 | - `GenericVector` = `Vector` 404 | - `List` = `Vector` 405 | - `ExpressionVector` = `Vector` 406 | 407 | - Within this documentation, the default type used will be `NumericVector` unless 408 | another data type is required to show a specific feature. 409 | 410 | - Constructors: 411 | - `Vector()` 412 | - `Vector(SEXP x)` 413 | - `Vector(const int &size, const stored_type &u)` 414 | - `Vector(const std::string &st)` 415 | - `Vector(const char *st)` 416 | - `Vector(const Vector &other)` 417 | - `Vector(const int &size)` 418 | - `Vector(const Dimension &dims)` 419 | - `Vector(const Dimension &dims, const U &u)` 420 | - `Vector(const Vector &other)` 421 | 422 | - By default, the vectors constructed from dimensions will always be 423 | initialized with all entries being zero (`0`) or an empty string (`""`). 424 | 425 | - For the majority of cases, the interface being used is that of the R to C++ 426 | interface that relies upon the `Vector(SEXP x)` constructor, which establishes 427 | a **pointer** to the underlying data. That is, the `Vector` object _points_ to 428 | the memory location of the `SEXP` R object in order to avoid copying the data 429 | into _C++_. The only exception to this rule is if the data passed is of a 430 | different type in which case a deep copy is performed _before_ a pointer is 431 | established. For example, if `numeric()` data is passed to `NumericVector` 432 | the correct handoff occurs. However, if `integer()` data were to be passed to 433 | a `NumericVector` a `clone()` would be made to type `numeric()` which has its 434 | pointer then assigned to the `NumericMatrix`. 435 | 436 | - Examples: 437 | 438 | ```{Rcpp rcpp_vector_ctor} 439 | SEXP A; 440 | NumericVector B(A); // from a SEXP 441 | 442 | // create a vector of length 5 filled with 0 443 | NumericVector C(5); 444 | // Output: 0 0 0 0 0 445 | 446 | // construct a filled vector of size 3 with 2.0 447 | NumericVector D = NumericVector(3, 2.0); 448 | // Output: 2 2 2 449 | 450 | // initialize empty numeric vector of size 5 451 | NumericVector D2 = no_init(5); 452 | 453 | // fill vector with 3.0 454 | D2.fill(3.0); 455 | // Output: 3 3 3 3 3 456 | 457 | // cloning (deep copy) 458 | NumericVector E = clone(D); 459 | // Output: 2 2 2 460 | ``` 461 | 462 | - See also: 463 | - [Vector Class doxygen documentation](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1Vector.html) 464 | - [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef) 465 | 466 | ------ 467 | 468 | ### Matrix {#matrix} 469 | 470 | - The main class for matrices is the templated `Matrix` class, which derives from 471 | a combination of both the `Vector` and `MatrixBase` types. Like the `Vector` 472 | class, `Matrix` uses the policy-based design pattern to manage the lifetime of 473 | its undelying `SEXP` via the template parameter `StoragePolicy`, which 474 | uses the `PreserveStorage` policy class by default. Matrices are 475 | instantiated as `Matrix`, where the value `RTYPE` is one of the 476 | following `SEXPTYPE`s: 477 | 478 | - `REALSXP` 479 | - `INTSXP` 480 | - `CPLXSXP` 481 | - `LGLSXP` 482 | - `STRSXP` 483 | - `VECSXP` 484 | - `RAWSXP` 485 | - `EXPRSXP` 486 | 487 | 488 | - For convenience, the following [`typedefs` have been defined](https://github.com/RcppCore/Rcpp/blob/6f81b4684481dbd9bb554dd95e66725fc3b63a8c/inst/include/Rcpp/vector/instantiation.h#L40-L50) in the `Rcpp` 489 | namespace: 490 | 491 | - `NumericMatrix` = `Matrix` 492 | - `RawMatrix` = `Matrix` 493 | - `IntegerMatrix` = `Matrix` 494 | - `ComplexMatrix` = `Matrix` 495 | - `LogicalMatrix` = `Matrix` 496 | - `CharacterMatrix` = `Matrix` 497 | - `StringMatrix` = `Matrix` 498 | - `GenericMatrix` = `Matrix` 499 | - `ListMatrix` = `Matrix` 500 | - `ExpressionMatrix` = `Matrix` 501 | 502 | 503 | - Within this documentation, the default type used will be `NumericMatrix` unless 504 | another data type is required to show a specific feature. 505 | 506 | - Constructors: 507 | - `Matrix()` 508 | - `Matrix(SEXP x)` 509 | - `Matrix(const int& nrows_, const int& ncols)` 510 | - `Matrix(const int& nrows_, const int& ncols, Iterator start)` 511 | - `Matrix(const int& n)` 512 | - `Matrix(const Matrix& other)` 513 | 514 | - By default, the matrices constructed from dimensions will always be 515 | initialized with all entries being zero (`0`) or empty strings (`""`) 516 | 517 | - For the majority of cases, the interface being used is that of the R to C++ 518 | interface that relies upon the `Matrix(SEXP x)` constructor, which establishes 519 | a **pointer** to the underlying data. That is, the `Matrix` object _points_ to 520 | the memory location of the `SEXP` R object in order to avoid copying the data 521 | into _C++_. The only exception to this rule is if the data passed is of a 522 | different type in which case a deep copy is performed _before_ a pointer is 523 | established. For example, if `numeric()` data is passed to `NumericMatrix` 524 | the correct handoff occurs. However, if `integer()` data were to be passed to 525 | a `NumericMatrix` a `clone()` would be made to type `numeric()` which has its 526 | pointer then assigned to the `NumericMatrix`. 527 | 528 | - Examples: 529 | 530 | ```{Rcpp rcpp_matrix_ctor} 531 | SEXP A; 532 | NumericMatrix B(A); // from a SEXP 533 | 534 | // create a square matrix (all elements set to 0.0) 535 | NumericMatrix C(2); 536 | // Output: 537 | // 0 0 538 | // 0 0 539 | 540 | // of a given size (all elements set to 0.0) 541 | NumericMatrix D(2, 3); 542 | // Output: 543 | // 0 0 0 544 | // 0 0 0 545 | 546 | // of a given size with dimensions (all elements set to 0.0) 547 | NumericMatrix D2(Dimension(3, 2)); 548 | // Output: 549 | // 0 0 550 | // 0 0 551 | // 0 0 552 | 553 | // initialize empty numeric matrix 554 | NumericMatrix D3 = no_init(2, 1); 555 | 556 | // fill matrix with 3.0 557 | D3.fill(3.0); 558 | // Output: 559 | // 3.0 560 | // 3.0 561 | 562 | // fill matrix using a vector 563 | NumericVector E = NumericVector(15, 2.0); 564 | NumericMatrix F = NumericMatrix(3, 5, E.begin()); 565 | // Output: 566 | // 2 2 2 2 2 567 | // 2 2 2 2 2 568 | // 2 2 2 2 2 569 | 570 | // cloning (explicit deep copy) 571 | NumericMatrix G = clone(F); 572 | ``` 573 | 574 | - See also: 575 | - [`Matrix` Class doxygen documentation](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1Matrix.html) 576 | - [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef) 577 | 578 | ### List {#list} 579 | 580 | - The `List` data structure is a `typedef` of templated `Vector` class based 581 | on the `RTYPE` of `VECSXP` that provides heterogenous storage class. As 582 | a result, the `List` class acts as a generic storage object that can 583 | simultaneously hold multiple different `RTYPE` structures. 584 | 585 | - Constructors: 586 | - `List()` 587 | - `List(SEXP x)` 588 | - `List(const int &size, const stored_type &u)` 589 | - `List(const std::string &st)` 590 | - `List(const char *st)` 591 | - `List(const Vector &other)` 592 | - `List(const int &size)` 593 | - `List(const Dimension &dims)` 594 | - `List(const Dimension &dims, const U &u)` 595 | - `List(const Vector &other)` 596 | 597 | - Unlike the `Vector` class, the `List` constructed from dimensions will have a 598 | `NULL` value set for each element unless a value is otherwise assigned. 599 | 600 | - Examples: 601 | 602 | ```{Rcpp rcpp_list_ctor} 603 | SEXP A; 604 | List B(A); // from a SEXP 605 | 606 | // create an empty List of size 2 607 | List C(2); 608 | // Output: 609 | // [[1]] 610 | // NULL 611 | // [[2]] 612 | // NULL 613 | 614 | // construct List of size 3 with one element containing 2.0 615 | List D = List(3, 2.0); 616 | // Output: 617 | // [[1]] 618 | // [1] 2 619 | // [[2]] 620 | // [1] 2 621 | // [[3]] 622 | // [1] 2 623 | 624 | // initialize empty list of size 3 625 | List D2 = no_init(3); 626 | 627 | // fill list one element equal to 3.0 628 | D2.fill(3.0); 629 | // Output: 630 | // [[1]] 631 | // [1] 3 632 | // [[2]] 633 | // [1] 3 634 | // [[3]] 635 | // [1] 3 636 | 637 | // cloning (deep copy) 638 | List E = clone(D); 639 | // Output: 640 | // [[1]] 641 | // [1] 2 642 | // [[2]] 643 | // [1] 2 644 | // [[3]] 645 | // [1] 2 646 | 647 | 648 | // Create a named list 649 | NumericVector F = NumericVector::create(1.2, 3.5); 650 | CharacterVector G = CharacterVector::create("a", "b", "c"); 651 | LogicalVector H = LogicalVector::create(true, false, false, true); 652 | 653 | // Create named list 654 | List F = List::create(Named("v1") = F, 655 | Named("v2") = G, 656 | _["v3"] = H); // Shorthand for Named("V3") 657 | // Output: 658 | // $v1 659 | // [1] 1.2 3.5 660 | // $v2 661 | // [1] "a" "b" "c" 662 | // $v3 663 | // [1] TRUE FALSE FALSE TRUE 664 | ``` 665 | 666 | - See also: 667 | - [`Vector`](#vector) 668 | - [Vector Class doxygen documentation](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1Vector.html) 669 | - [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef) 670 | 671 | ### DataFrame {#dataframe} 672 | 673 | - The `DataFrame` data structure is a typedef of the `DataFrame_Impl` class, 674 | which is a special extension of the templated `Vector` class 675 | that allows for a collection of heterogenous `Vector`'s of the same length. 676 | As the crux of the implementation of is 677 | [policy-based design](https://en.wikipedia.org/wiki/Policy-based_design) focused, 678 | much of the behavior of `DataFrame` is determined by the policy classes it 679 | inherits from 680 | 681 | - `RObjectMethods` 682 | - `StoragePolicy` 683 | - `SlotProxyPolicy` 684 | - `AttributeProxyPolicy` 685 | - `NamesProxyPolicy` 686 | 687 | as well as the CRTP base class `VectorBase`. 688 | 689 | - Constructors: 690 | 691 | - `DataFrame()` 692 | - `DataFrame(SEXP x)` 693 | - `DataFrame(const DataFrame &other)` 694 | - `DataFrame(const T &obj)` 695 | 696 | - **Caveat:** All `DataFrame` columns _must_ be named. Failure to name the columns 697 | will result in the run time error of: 698 | 699 | > not compatible with STRSXP 700 | 701 | since Rcpp uses an internal call to _R_ to create the `DataFrame`. 702 | 703 | - Examples: 704 | 705 | ```{Rcpp rcpp_dataframe_ctor} 706 | SEXP A; 707 | DataFrame B(A); // from a SEXP 708 | 709 | // Create Data 710 | NumericVector C = NumericVector::create(5.8, 9.1, 3.2); 711 | CharacterVector D = CharacterVector::create("a", "b", "c"); 712 | LogicalVector E = LogicalVector::create(true, false, false); 713 | 714 | // Create a new dataframe 715 | DataFrame G = DataFrame::create(Named("C") = C, 716 | _["D"] = D, // shorthand for Named("D") 717 | Named("E") = E); 718 | ``` 719 | 720 | - See also: 721 | - [`Vector`](#vector) 722 | - [DataFrame `typedef`](http://dirk.eddelbuettel.com/code/rcpp/html/DataFrame_8h.html) 723 | - [`DataFrame_Impl` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1DataFrame__Impl.html) 724 | - [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef) 725 | 726 | 727 | ### RObject {#robject} 728 | 729 | - The `RObject` data structure is a typedef of the `RObject_Impl` class. Principally, 730 | the class can be viewed as the glue of Rcpp due to [policy-based design](https://en.wikipedia.org/wiki/Policy-based_design) 731 | principles. In turn, the `RObject` class really acts as a "shell" that stores 732 | properties of the following policies: 733 | 734 | - `PreserveStorage`: Member functions that provide the `SEXP` _R_ object 735 | alongside ways to modify and update the object. 736 | - `SlotProxyPolicy`: Member functions related to _only_ manipulating S4 737 | objects. 738 | - `AttributeProxyPolicy`: Member functions that modify attribute information 739 | of the _R_ object. 740 | - `RObjectMethods`: Member functions that provide descriptors of the _R_ 741 | object such as type, object oriented programming (S3/S4) system, and 742 | `NULL` status. 743 | 744 | - Constructors: 745 | 746 | - `RObject()` 747 | - `RObject(const RObject &other)` 748 | - `RObject(const GenericProxy &proxy)` 749 | 750 | - Examples: 751 | 752 | ```{Rcpp robject_example} 753 | // Extract attribute information via AttributeProxyPolicy 754 | RObject A; 755 | RObject B = A.attr("dim"); 756 | ``` 757 | 758 | - See also: 759 | - [Modern C++ Design](http://en.wikipedia.org/wiki/Modern_C++_Design) 760 | - [`RObject_Impl` class](http://dirk.eddelbuettel.com/code/rcpp/html/RObject_8h.html) 761 | - [`RObjectMethods` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1RObjectMethods.html) 762 | - [`StoragePolicy` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1StoragePolicy.html) 763 | - [`SlotProxyPolicy` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1SlotProxyPolicy.html) 764 | - [`AttributeProxyPolicy` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1AttributeProxyPolicy.html) 765 | - [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef) 766 | 767 | ## Member Functions {#member-functions} 768 | 769 | ### Operators {#ops} 770 | 771 | - Operators allow for operations to take place between two different `Vector` or `Matrix` objects. 772 | The operations are defined to works in an element-wise fashion where applicable. 773 | 774 | - Viable mathematical operations that are able to be performed. 775 | 776 | | Operation | Definition | Vector-Vector | Vector-Scalar | Vector-Matrix | Matrix - Matrix | Matrix - Scalar | 777 | |:---------:|:------------------:|:-------------:|:--------------:|:-------------:|:---------------:|:---------------:| 778 | | + | Addition | Yes | Yes | No | No | Yes | 779 | | - | Subtraction | Yes | Yes | No | No | Yes | 780 | | / | Division | Yes | Yes | No | No | Yes | 781 | | * | Multiplication | Yes | Yes | No | No | Yes | 782 | 783 | 784 | - Logical Operations 785 | 786 | | Operation | Definition | Vector-Vector | Vector-Scalar | Vector-Matrix | Matrix - Matrix | Matrix - Scalar | 787 | |:---------:|:-------------------------:|:-------------:|:--------------:|:---------------:|:---------------:|:---------------:| 788 | | == | Equality | Yes | Yes | No | No | Yes | 789 | | != | Non-equality | Yes | Yes | No | No | Yes | 790 | | >= | Greater than or equal to | Yes | Yes | No | No | Yes | 791 | | <= | Less than or equal to | Yes | Yes | No | No | Yes | 792 | | < | Less than | Yes | Yes | No | No | Yes | 793 | | > | Greater than | Yes | Yes | No | No | Yes | 794 | | ! | Negate | Yes | Yes | No | No | Yes | 795 | 796 | - Examples: 797 | 798 | ```{Rcpp sugar_math_ops} 799 | // Sample data 800 | NumericVector A = NumericVector::create(1, 2, 3, 4); 801 | NumericVector B = NumericVector::create(2, 3, 4, 5); 802 | 803 | // --- Addition 804 | 805 | // Add a vector and scalar 806 | NumericVector H = A + 2.0; 807 | // Output: 3 4 5 6 808 | 809 | // Add a vector and another vector 810 | NumericVector I = A + B; 811 | // Output: 3 5 7 9 812 | 813 | // --- Subtraction 814 | 815 | // Subtract a scalar from a vector 816 | NumericVector J = 2.0 - A; 817 | // Output: 1 0 -1 -2 818 | 819 | // Subtract vectors 820 | NumericVector K = A - B; 821 | // Output: -1 -1 -1 -1 822 | 823 | // --- Multiplication 824 | 825 | // Multiple by scalar 826 | NumericVector L = 3 * A; 827 | // Output: 3 6 9 12 828 | 829 | // Multiple Vectors 830 | NumericVector M = A * B; 831 | // Output: 2 6 12 20 832 | 833 | // --- Division 834 | 835 | // Divide by scalar 836 | NumericVector L = 1 / A; 837 | // Output: 1.0000000 0.5000000 0.3333333 0.2500000 838 | 839 | // Divide Vectors 840 | NumericVector M = A / B; 841 | // Output: 0.5000000 0.6666667 0.7500000 0.8000000 842 | 843 | // --- All together 844 | NumericVector res = 3.0 * A - 1.0 / B + A + B + 5.0; 845 | // Output: 10.50000 15.66667 20.75000 25.80000 846 | ``` 847 | 848 | ### Dimensional Information {#diminfo} 849 | 850 | | | | 851 | |:----------------------|:---------------------------------------------| 852 | | `.nrow()`,`.rows()` | number of rows in a `Matrix`, `DataFrame` | 853 | | `.ncol()`,`.cols()` | number of columns in a `Matrix`, `DataFrame` | 854 | | `.size()`,`.length()` | number of items in a `Matrix`, `Vector` | 855 | 856 | - Return type is that of an `int`, `unsigned int`, or `R_xlen_t` 857 | 858 | - Note: As of Rcpp 0.13.0, new size attribute accessors were added to the 859 | `DataFrame` class that mimick those available in `Matrix`. Previously, to 860 | obtain the number of columns, one would have to use the `.size()` or `.length()` 861 | member function. In addition, the number of observations previously had to 862 | be obtained by `.nrows()`. 863 | 864 | - Examples: 865 | 866 | ```{Rcpp dimensional_info} 867 | // --- Vector Example 868 | NumericVector X(3); 869 | 870 | int nelem = X.size(); // Output: 3 871 | int nlens = X.length(); // Output: 3 872 | 873 | Rcout << "Vector X has " << nelem << " elements." << std::endl; 874 | 875 | // --- Matrix Example 876 | NumericMatrix X(4,5); 877 | 878 | int rows = X.nrow(); // Output: 4 879 | int cols = X.ncols(); // Output: 5 880 | int elems = X.size(); // Output: 20 881 | 882 | Rcout << "Matrix Y has " << rows << " rows and " << cols << " columns." << std::endl; 883 | ``` 884 | 885 | 886 | ### Element Access {#elem-access} 887 | 888 | - Described within this section is the ability to access elements using 889 | the position, categorical, and logical indexing systems. 890 | 891 | - The access system provides two retrieval methods for all classes 892 | that differ in computational time to obtain values from objects. 893 | - The preferred method to access elements is `()`, which that takes slightly 894 | longer due to a bounds check being performed that verifies whether the 895 | requested element is within the access scope. Furthermore, if the 896 | requested element is out of bounds, an exception is raised and the program 897 | stops. 898 | - The other method uses `[]`, which does _not_ perform a bounds check and 899 | assumes that the access scope is valid. If an element is out of bounds, 900 | the behavior exhibited will be undefined and may cause havoc with later 901 | parts of a procedure. Only use this form of accessor if the procedure has 902 | been thoroughly tested and debugged. 903 | 904 | - Note: Using accessors without a bounds check is **not** recommended unless 905 | the code has been thoroughly tested as undefined behavior (UB) may emerge. UB 906 | is very problematic. 907 | 908 | #### Position Access {#position-access} 909 | 910 | - Access a single element or object using a positional index. 911 | - `(i)` provides the *i*th element or object in addition to performing a 912 | bounds check that ensures the requested index is a valid location. 913 | - `[i]` similar to the previous case, but does so *without* a bounds check. 914 | - `at(i,j)` provides the *i,j*th element of a `Matrix` with a bounds check. 915 | - `(i,j)` provides the *i,j*th element of a `Matrix` *without* a bounds check. 916 | 917 | - **Caveat:** Using either `[i]` or `(i)` on `List` and `DataFrame`, 918 | provides the object (e.g. `Vector`) at position *i* whereas the use on 919 | `Vector` or `Matrix` will provide a scalar element (e.g. `double`). 920 | 921 | - Note: Unlike _R_, there is no `[]` subset operator for matrices with _C++_. 922 | The reason for the lack of `operator[]` relates to a fundamental design choice 923 | made by the creators of C++ related to the presence of the 924 | [`operator,`](http://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator). 925 | In essence, after the complete evaluation of the first coordinate `x` and disposal 926 | of the results, only then is the second coordinate `y` able to be evaluated. 927 | Unfortunately, this yields the following `-Wall` issue: 928 | 929 | > left operand of comma operator has no effect. 930 | 931 | Therefore, the only viable matrix subset operators within C++ are `operator()` and `operator at()` provide subset operations. 932 | 933 | - Examples: 934 | 935 | ```{Rcpp position_access} 936 | // Create data 937 | NumericVector A = NumericVector::create(1, 2, 3, 4); 938 | CharacterVector C = CharacterVector::create("B", "D", "E", "F"); 939 | 940 | // --- Vector 941 | 942 | // Retrieve the first value from A. (C++ indices start at 0 not 1!) 943 | double a = A(0); 944 | // Output: 1 945 | 946 | // Modify the last value using unbound accessor 947 | // Warning: Make sure the point is valid! 948 | A[3] = 5; 949 | 950 | // --- Matrix 951 | 952 | // Create matrix with elements in A 953 | NumericMatrix B(2, 2, A.begin()); 954 | 955 | // Output: 956 | // 1 3 957 | // 2 5 958 | 959 | // Extract Value at 2, 1 960 | double val_r1c0 = B(1, 0); 961 | // Output: 2 962 | 963 | // Modify value at 1, 2 964 | B(0, 1) = 4; 965 | 966 | // Output: 967 | // 1 4 968 | // 2 5 969 | 970 | // The following shows a bounds throw error 971 | // B.at(1, 2) = 4; 972 | 973 | // --- List 974 | 975 | // Create a List 976 | List D = List::create(Named("A") = A, 977 | _["C"] = C); // shorthand for Named("C") 978 | 979 | // Extract A from List 980 | NumericVector E = D[0]; 981 | 982 | double val2 = E[1]; 983 | // Output: 2 984 | 985 | // Extract B from List 986 | CharacterVector F = D[1]; 987 | 988 | // --- Data Frame 989 | 990 | // Create a DataFrame 991 | DataFrame G = DataFrame::create(Named("A") = A, 992 | _["C"] = C); // shorthand for Named("C") 993 | 994 | // Extract A from DataFrame 995 | NumericVector E = DF[0]; 996 | ``` 997 | 998 | #### Categorical Access {#categorical-access} 999 | 1000 | - Access element by name within a `Vector`, `List`, or `DataFrame`. 1001 | - `(NAME)` provides the element associated with the `NAME` in addition to 1002 | performing a bounds check that ensures the requested `NAME` exists. 1003 | - `[NAME]` similar to the previous case, but does so *without* a bounds check. 1004 | 1005 | - Examples: 1006 | 1007 | ```{Rcpp string_access} 1008 | // Create sample data 1009 | NumericVector A = NumericVector::create(Named("Go") = 3, 1010 | Named("To") = 4, 1011 | _["My"] = 5, // shorthand Named("My") 1012 | _["Pi"] = 1); 1013 | // Output: (names only printed in R!) 1014 | // Go To My Pi 1015 | // 3 4 5 1 1016 | 1017 | NumericVector B = NumericVector::create(2, 5, 8, 9, 3, 7); 1018 | 1019 | // Alternative way to set name values 1020 | B.names() = CharacterVector::create("Bears","Lions","and","Tigers", "Oh", "My"); 1021 | // Output: (names only printed in R!) 1022 | // Bears Lions and Tigers Oh My 1023 | // 2 5 8 9 3 7 1024 | 1025 | // --- Vector 1026 | 1027 | double val_num = A["To"]; 1028 | // Output: 1029 | // To 1030 | // 4 1031 | 1032 | // Subset by vector 1033 | CharacterVector C = CharacterVector::create("My", "Pi"); 1034 | 1035 | NumericVector D = A[C]; 1036 | // Output: (names only printed in R!) 1037 | // My Pi 1038 | // 5 1 1039 | 1040 | // Modify values in vector 1041 | NumericVector E = NumericVector::create(1, 2); 1042 | A[C] = E; 1043 | // Output: 1044 | // Go To My Pi 1045 | // 3 4 1 2 1046 | 1047 | // --- List 1048 | 1049 | // Create a List 1050 | List F = List::create(Named("A") = A, 1051 | _["B"] = B); // shorthand for Named("B") 1052 | 1053 | // Extract A from List 1054 | NumericVector G = F["A"]; 1055 | 1056 | double val_go = G["Go"]; 1057 | // Output: 3 1058 | 1059 | // --- Data Frame 1060 | 1061 | // Create a DataFrame 1062 | DataFrame H = DataFrame::create(Named("A") = A, 1063 | _["B"] = B); // shorthand for Named("B") 1064 | 1065 | // Extract B vector from DataFrame 1066 | NumericVector I = H["B"]; 1067 | 1068 | double val_lions = I["Lions"]; 1069 | // Output: 5 1070 | ``` 1071 | 1072 | #### Logical Access {#logical-access} 1073 | 1074 | - Access element by boolean values within a `Vector`, `List`, or `DataFrame`. 1075 | - `(BOOL)` provides only the elements associated `true` logical 1076 | condition in addition to performing a bounds check that ensures the 1077 | requested element at the `BOOL` location exists. 1078 | - `[BOOL]` similar to the previous case, but does so *without* a bounds check. 1079 | 1080 | - **Caveat:** The `BOOL` must be a `LogicalVector` of equal size to the object 1081 | being subset. 1082 | 1083 | - Examples: 1084 | 1085 | ```{Rcpp logical_access} 1086 | // Sample data 1087 | NumericVector A = NumericVector::create(4, 3, 1, 2); 1088 | // Output: 4 3 1 2 1089 | 1090 | // Logical Subset 1091 | LogicalVector B = LogicalVector::create(true, false, false, true); 1092 | // Output: TRUE FALSE FALSE TRUE 1093 | 1094 | NumericVector C = A[B]; 1095 | // Output: 4 2 1096 | 1097 | // Replace Values 1098 | NumericVector D = NumericVector::create(8, 6); 1099 | 1100 | // Logical Replacement 1101 | A[B] = D; 1102 | // Output: 4 8 6 2 1103 | ``` 1104 | 1105 | ### Subset Views {#subview} 1106 | 1107 | 1108 | ### Iterators {#iterators} 1109 | 1110 | - C++ Standard Template Library (STL) styled random access iterators exist underlying 1111 | the `Vector` and `Matrix` classes. 1112 | 1113 | - Iterator accessor: 1114 | 1115 | | | | 1116 | |:-------------|:------------------------------------| 1117 | | `·begin()` | pointer to the start of the vector | 1118 | | `·end()` | pointer to one past end of vector | 1119 | 1120 | 1121 | - Kinds of Iterators: 1122 | 1123 | | | | 1124 | |:------------------------------|:------------------------------------------------------------| 1125 | | `NumericVector::iterator` | allows for read/write access to elements (stored by column) | 1126 | | `ComplexVector::iterator` | | 1127 | | `IntegerVector::iterator` | | 1128 | | `LogicalVector::iterator` | | 1129 | | `CharacterVector::iterator` | | 1130 | | `RawVector::iterator` | | 1131 | | `ExpressionVector::iterator` | | 1132 | | `GenericVector::iterator` | | 1133 | | `NumericMatrix::iterator` | | 1134 | | `ComplexMatrix::iterator` | | 1135 | | `IntegerMatrix::iterator` | | 1136 | | `RawMatrix::iterator` | | 1137 | | `LogicalMatrix::iterator` | | 1138 | | `CharacterMatrix::iterator` | | 1139 | | `StringMatrix::iterator` | | 1140 | | `ExpressionMatrix::iterator` | | 1141 | | `GenericMatrix::iterator` | | 1142 | | `ListMatrix::iterator` | | 1143 | 1144 | 1145 | | | | 1146 | |:------------------------------------|:------------------------------------------------------| 1147 | | `NumericVector::const_iterator` | allows for read access to elements (stored by column) | 1148 | | `ComplexVector::const_iterator` | | 1149 | | `IntegerVector::const_iterator` | | 1150 | | `LogicalVector::const_iterator` | | 1151 | | `CharacterVector::const_iterator` | | 1152 | | `RawVector::const_iterator` | | 1153 | | `ExpressionVector::const_iterator` | | 1154 | | `GenericVector::const_iterator` | | 1155 | | `NumericMatrix::const_iterator` | | 1156 | | `ComplexMatrix::const_iterator` | | 1157 | | `IntegerMatrix::const_iterator` | | 1158 | | `RawMatrix::const_iterator` | | 1159 | | `LogicalMatrix::const_iterator` | | 1160 | | `CharacterMatrix::const_iterator` | | 1161 | | `StringMatrix::const_iterator` | | 1162 | | `ExpressionMatrix::const_iterator` | | 1163 | | `GenericMatrix::const_iterator` | | 1164 | | `ListMatrix::const_iterator` | | 1165 | 1166 | 1167 | ```{Rcpp} 1168 | // Sample Data 1169 | NumericVector A = NumericVector::create(-1, 3.2, 0, 14.2, 38.6); 1170 | 1171 | // --- Use iterators to compute sum 1172 | double val_total = 0; 1173 | 1174 | for(NumericVector::iterator iter = A.begin(); iter != A.end(); ++iter) { 1175 | val_total += *iter; 1176 | } 1177 | 1178 | Rcpp::Rcout << "Sum Value is " << val_total << std::endl; 1179 | // Output: Sum Value is 55 1180 | ``` 1181 | 1182 | ### STL-style container functions {#stl-functions} 1183 | 1184 | - There exists a special class of member functions that mimic how C++ Standard 1185 | Template Library (STL) implement member functions for container architecture 1186 | such as `vector`, `deque`, and `list`. 1187 | 1188 | - Member functions that do _not_ alter the **size** of the Rcpp object 1189 | 1190 | | Member | Description | 1191 | |:-----------------------|:--------------------------------------------| 1192 | | `operator()` | Access elements _with_ checking range | 1193 | | `operator[]` | Access elements _without_ checking range | 1194 | | `.length()`, `.size()` | Amount of elements in the collection | 1195 | | `.fill(u)` | Fill the collection with element `u` | 1196 | 1197 | - Member functions that _do_ alter the **size** of the Rcpp object and result 1198 | in the object being recreated. 1199 | 1200 | | Member | Description | 1201 | |:-----------------|:----------------------------------------------------| 1202 | | `·push_back(x)` | Insert `x` at end of vector, grows vector | 1203 | | `·push_front(x)` | Insert `x` at beginning of vector, grows vector | 1204 | | `·insert(i, x)` | Insert `x` at the _i_^th^ position of, grows vector | 1205 | | `·erase(i)` | Remove element at _i_^th^ position, shrinks vector | 1206 | 1207 | - **Warning:** Using any of the above member functions to grow or shrink 1208 | an Rcpp object will result in a severe degregation of performance. The 1209 | reason why is because Rcpp objects are proxy models that serve as shallow 1210 | wrappers around R objects. Thus, when an Rcpp object is expanded or shrunk, 1211 | the data must be _copied_ from the original object into a new object. 1212 | Therefore, it is highly recommended to convert the Rcpp object to an STL 1213 | object that can easily be grown or shrunk if the sample size is _not_ known 1214 | in advance. 1215 | 1216 | ### Static Member Functions {#static-members} 1217 | 1218 | #### create {#create} 1219 | 1220 | | | 1221 | |:------------------------| 1222 | | **::create(X, Y)** | 1223 | | **::create(X, Y, ...)** | 1224 | 1225 | 1226 | **::create(X, Y, ...)** 1227 | 1228 | - Initializes a `Vector`, `List`, or `DataFrame` by combining objects together 1229 | sequentially in a manner similar to `c(1, 2)` in *R*. 1230 | 1231 | - In the case of a `Vector`, the values *X* and *Y* must be an atomic value of 1232 | the same underlying type *T*, where *T* is one of the following: 1233 | - `int` 1234 | - `double` 1235 | - `std::complex / Rcomplex` 1236 | - `bool` 1237 | 1238 | - For either a `DataFrame` or `List`, *X*, *Y* are allowed to be any combination 1239 | of `Vector`, `Matrix`, and the previously mentioned supported atomic types. 1240 | 1241 | - `create` is defined for any number of arguments between 1 and 20, inclusive. 1242 | 1243 | - When constructing examples, it is often preferable to use `create` method 1244 | to build a vector. 1245 | 1246 | - Examples: 1247 | 1248 | ```{Rcpp static_create} 1249 | // Construct a vector 1250 | NumericVector A = NumericVector::create(4.2, 1.9, 2, 3.5); 1251 | // Output: 4.2 1.9 2.0 3.5 1252 | 1253 | IntegerVector B = IntegerVector::create(1, 2); 1254 | // Output: 1 2 1255 | 1256 | CharacterVector C = CharacterVector::create("a", "b", "c", "d"); 1257 | // Output: "a" "b" "c" "d" 1258 | 1259 | 1260 | // Unnammed list creation 1261 | List D = List::create(1.5, 2.3, 4.5); 1262 | // Must be returned into R for output! 1263 | // Output: 1264 | // [[1]] 1265 | // [1] 1.5 1266 | // [[2]] 1267 | // [1] 2.3 1268 | // [[3]] 1269 | // [1] 4.5 1270 | 1271 | // Named list creation 1272 | List E = List::create(Named("B") = B, 1273 | _["nval"] = 2.5); // shorthand for Named("nval") 1274 | // Must be returned into R for output! 1275 | // $B 1276 | // [1] 1 2 1277 | // 1278 | // $val 1279 | // [1] 2.5 1280 | 1281 | // DataFrame creation 1282 | // The number of elements in vectors must _match_ 1283 | DataFrame F = DataFrame::create(Named("A") = A, 1284 | _["C"] = C); // shorthand for Named("C") 1285 | // Must be returned into R for output! 1286 | // Output: 1287 | // A C 1288 | // 4.2 a 1289 | // 1.9 b 1290 | // 2.0 c 1291 | // 3.5 d 1292 | ``` 1293 | 1294 | 1295 | 1296 | #### get_na() {#get_na} 1297 | 1298 | - Obtain the correct missing value constant for the given _RTYPE_ associated 1299 | with the Rcpp data structure. 1300 | 1301 | - Examples: 1302 | 1303 | ```{Rcpp static_get_na} 1304 | // Construct a vector 1305 | NumericVector A = NumericVector::create(NA_REAL, -1, NumericVector::get_na(), 0); 1306 | // Output: NA -1 NA 0 1307 | 1308 | A[3] = NumericVector::get_na(); 1309 | // Output: NA -1 NA NA 1310 | ``` 1311 | 1312 | - See also: 1313 | - [Setting Infinite, Missingness, and NaN Values](#nan-constants) 1314 | - [Sugar: Finite, Infinite, Missingness, and NaN Detection](#sugar-nan) 1315 | 1316 | #### is_na() {#is_na_static} 1317 | 1318 | - Determine whether an element within the Rcpp data structure matches a missing 1319 | constant of the given _RTYPE_. 1320 | 1321 | - Examples: 1322 | 1323 | ```{Rcpp} 1324 | // Construct a vector 1325 | NumericVector A = NumericVector::create(NA_REAL, -1, NumericVector::get_na(), 0); 1326 | 1327 | int n = A.size(); 1328 | LogicalVector B(n); 1329 | 1330 | for (int i = 0; i < n; ++i) { 1331 | B[i] = NumericVector::is_na(A[i]); 1332 | } 1333 | 1334 | Rcout << "NA Presence: " << B << std::endl; 1335 | // Output: NA Presence: 1 0 1 0 1336 | ``` 1337 | 1338 | - See also: 1339 | - [Setting Infinite, Missingness, and NaN Values](#nan-constants) 1340 | - [Missing Values and NaN Detection](#missingness) 1341 | 1342 | #### import(InputIterator first, InputIterator last) {#import} 1343 | 1344 | 1345 | #### import_transform(InputIterator first, InputIterator last, F f) {#import-transform} 1346 | 1347 | 1348 | #### diag(int size, const U &diag_value) {#diag-static} 1349 | 1350 | - This method is available only for the `Matrix` class. 1351 | 1352 | - Examples: 1353 | 1354 | ```{Rcpp diag_static} 1355 | 1356 | ``` 1357 | 1358 | #### eye(int n) {#eye} 1359 | 1360 | - This method is available only for the `Matrix` class. 1361 | 1362 | - Examples: 1363 | 1364 | ```{Rcpp eye_static} 1365 | 1366 | ``` 1367 | 1368 | #### ones(int n) {#ones} 1369 | 1370 | - This method is available only for the `Matrix` class. 1371 | 1372 | - Examples: 1373 | 1374 | ```{Rcpp ones_static} 1375 | 1376 | ``` 1377 | 1378 | #### zeros(int n) {#zeros} 1379 | 1380 | - This method is available only for the `Matrix` class. 1381 | 1382 | - Examples: 1383 | 1384 | ```{Rcpp zeros_static} 1385 | 1386 | ``` 1387 | 1388 | ## Environment 1389 | 1390 | 1391 | ## Function 1392 | 1393 | ## Language 1394 | 1395 | ## XPtr 1396 | 1397 | ## S4 Classes 1398 | 1399 | ## Exception Handling {#exception-handling} 1400 | 1401 | ### External Exception Classes {#external-exception-clasess} 1402 | 1403 | - Rcpp provides support for static and dynamic error messages. 1404 | - Static error messages rely upon only a `string` being passed into the function. 1405 | - Dynamic error messages must have a `string` with `printf`-like format 1406 | identifiers (see table for a list of common specifiers) followed by an 1407 | appropriate number of parameters (e.g `param1`, `param2`, ...). 1408 | - **Note:** Under C++98, there is a limit of 10 parameters for constructing 1409 | a dynamic error message whereas C++11 or greater lacks this limitation. 1410 | 1411 | - Error messages are sent over standard error (`STDERR`) stream 1412 | instead of standard input (`STDIN`) stream like `Rcout<<`. This is beneficial 1413 | as scripts that are not run interactively (e.g. over a distributed computing 1414 | node) will typically report to a different log directory customized to 1415 | warn the developer of an error regarding their job. 1416 | 1417 | - Common `printf` identifiers 1418 | 1419 | | specifier | Input | Example | 1420 | |:------------:|:------------------------------:|:-----------:| 1421 | | `%i` or `%d` | Signed integer | -42, 10 | 1422 | | `%u` | Unsigned integer | 10 | 1423 | | `%f` | Decimal floating point | 3.14 | 1424 | | `%e` | Scientific notation, lowercase | 1.5379e+6 | 1425 | | `%E` | Scientific notation, uppercase | 1.5379E+6 | 1426 | | `%c` | Character | x | 1427 | | `%s` | String | James | 1428 | 1429 | 1430 | #### `stop(...)` {#stop} 1431 | 1432 | - End the present execution of _C++_ code, return control to _R_ session, 1433 | and print an error message to the _R_ console. 1434 | 1435 | ```{Rcpp stop_ex} 1436 | // Static stop message 1437 | stop("Uh oh, we ran into an error."); 1438 | 1439 | // Dynamic stop message 1440 | int index = 100; 1441 | std::string vec_name = "toad"; 1442 | stop("Whoops, the index %i is bad at %s", index, vec_name); 1443 | ``` 1444 | 1445 | #### `warning(...)` {#warning} 1446 | 1447 | - Triggers a warning message to be displayed in the _R_ console while **not** 1448 | aborting the _C++_ execution. 1449 | 1450 | 1451 | ```{Rcpp stop_ex} 1452 | // Static warning 1453 | warning("Hey, was that supposed to do that?"); 1454 | 1455 | // Dynamic warning 1456 | std::string vec_name = "toad"; 1457 | warning("Houston, I think we have a problem at %s. Do you copy?", vec_name); 1458 | ``` 1459 | 1460 | 1461 | **[Internal Exception Classes](#internal-exception-clasess)** 1462 | 1463 | 1464 | 1465 | ### Internal Exception Classes {#internal-exception-clasess} 1466 | 1467 | 1468 | #### Simple Exceptions {#simple-exception} 1469 | 1470 | #### Exceptions {#exception} 1471 | 1472 | #### Advanced exceptions {#advanced-exception} 1473 | 1474 | 1475 | 1476 | 1477 | ## Sugar {#sugar} 1478 | 1479 | - The objective behind _Rcpp sugar_ is to provide a subset of the 1480 | high-level _R_ syntax in _C++_. For instance, part of the functionality 1481 | behind the [`table( X )`](#table) function can be 1482 | 1483 | - Unless otherwise noted, if a `Matrix` is supplied, then the `Matrix` is 1484 | corcered into column-form vectors before having the sugar functional procedure 1485 | performed. For example, given a 2x2 matrix the results of the function call 1486 | will go R1C1, R2C1, R1C2, and R2C2 where _R_ stands for Row and 1487 | _C_ for column. 1488 | 1489 | ### Logical Operations {#sugar-logic-ops} 1490 | 1491 | - Boolean functions that provide a way to analyze the data are provided within. 1492 | 1493 | #### ifelse( CONDITION, TRUEVAL, FALSEVAL) {#if-else} 1494 | 1495 | - Vectorized `if-else` assignment of elements dependent on the `CONDITION` 1496 | being `true` (`TRUEVAL`) or `false` (`FALSEVAL`). 1497 | 1498 | - To use the vectorized `if-else` the following criteria must be met: 1499 | - `CONDITION`: A `LogicalVector` or a sugar expression that evalutes to a `LogicalVector` 1500 | - `TRUE`/`FALSE`: either 1501 | 1. two compatible sugar expression (same *RTYPE*, same length), OR 1502 | 2. one sugar expression and one compatible primitive (same *RTYPE*) 1503 | 1504 | - **Caveat:** Unlike the _R_ equivalent, there is no recycling the occurs if 1505 | the vectors are of different lengths. In said cases, an error will be raised 1506 | at runtime indicating the length difference. 1507 | 1508 | ```{Rcpp vectorized_ifelse} 1509 | // Create data 1510 | NumericVector A = NumericVector::create(5, 1, 8, 3); 1511 | NumericVector B = NumericVector::create(2, 4, 6, 11); 1512 | 1513 | // a.) Vectors of the same length and type 1514 | NumericVector C = ifelse(A < B, A, (A + B)*B); 1515 | // Output: 14 1 84 3 1516 | 1517 | // b.) One vector and one constant 1518 | NumericVector D = ifelse(A > B, A, 2); 1519 | // Output: 5 2 8 2 1520 | ``` 1521 | 1522 | #### Single Logical Result {#single-logical} 1523 | 1524 | | | | 1525 | |:------------------|:------------------| 1526 | | **is_true( X )** | **is_false( X )** | 1527 | 1528 | - Convert the result state of `any( CONDITION )` and `all( CONDITION )` from the 1529 | `SingleLogicalResult` template class to an atomic value `bool` evaluated 1530 | as either `true` or `false` dependent on whether the call to `is_true( X )` or 1531 | `is_false( X )` is matched. 1532 | 1533 | - For example, if `any( CONDITION )` evaluates to `false` than `is_true( X )` 1534 | will return `false` but `is_false( X )` will return `true`. 1535 | 1536 | - Examples: 1537 | 1538 | ```{Rcpp single_logical} 1539 | IntegerVector A = seq_len(3); 1540 | // Output: 1 2 3 1541 | IntegerVector B = clone(A) - 1; 1542 | // Output: 0 1 2 1543 | 1544 | bool check_state_true = is_true( any(A > B) ); 1545 | // Output: true 1546 | 1547 | bool check_state_false = is_false( any(A > B) ); 1548 | // Output: false 1549 | 1550 | // Without using the above functions, a compile time error will trigger 1551 | // on assignment to bool. 1552 | // bool check_state_error = any( A > B ); 1553 | // Error: invalid use of incomplete type 'class Rcpp::sugar::forbidden_conversion' 1554 | // class conversion_to_bool_is_forbidden 1555 | ``` 1556 | 1557 | - See also: 1558 | - [any](#any) 1559 | - [all](#all) 1560 | 1561 | #### all( X ) {#all} 1562 | 1563 | - Tests if *all* elements in a `LogicalVector` or `LogicalMatrix` are `true`. 1564 | 1565 | - The actual return type of `all(X)` is an instance of the 1566 | `SingleLogicalResult` template class, but the functions `is_true` 1567 | and `is_false` may be used to convert the return value to `bool`. 1568 | 1569 | - Examples: 1570 | 1571 | ```{Rcpp logical_all} 1572 | NumericVector A = NumericVector::create(1.0, 2.0, 3.0, 4.0); 1573 | 1574 | Rcout 1575 | << std::boolalpha 1576 | << "all(A < 5): " << is_true(all(A < 5)) << "\n" 1577 | << "all(A < 4): " << is_true(all(A < 4)) << "\n" 1578 | << "all(!is_na(A)): " << is_true(all(!is_na(A))) 1579 | << "\n\n"; 1580 | // Output: 1581 | // all(A < 5): true 1582 | // all(A < 4): false 1583 | // all(!is_na(A)): true 1584 | 1585 | NumericMatrix B(2, 2, A.begin()); 1586 | 1587 | Rcout 1588 | << std::boolalpha 1589 | << "all(B < 5): " << is_true(all(B < 5)) << "\n" 1590 | << "all(B < 4): " << is_true(all(B < 4)) << "\n" 1591 | << "all(!is_na(B)): " << is_true(all(!is_na(B))) 1592 | << "\n\n"; 1593 | // Output: 1594 | // all(B < 5): true 1595 | // all(B < 4): false 1596 | // all(!is_na(B)): true 1597 | 1598 | Rcout 1599 | << std::boolalpha 1600 | << "all({true, true, true}): " 1601 | << is_true(all(LogicalVector::create(true, true, true))) << "\n" 1602 | << "all({true, true, false}): " 1603 | << is_true(all(LogicalVector::create(true, true, false))) 1604 | << std::endl; 1605 | // Output: 1606 | // all({true, true, true}): true 1607 | // all({true, true, false}): false 1608 | ``` 1609 | 1610 | - See also: 1611 | - [any](#any) 1612 | - [is_true](#single-logical) 1613 | - [is_false](#single-logical) 1614 | - [is_na](#is-na) 1615 | 1616 | #### any( X ) {#any} 1617 | 1618 | - Tests if *any* elements in a `LogicalVector` or `LogicalMatrix` are `true`. 1619 | 1620 | - The actual return type of `any(X)` is an instance of the 1621 | `SingleLogicalResult` template class, but the functions `is_true` 1622 | and `is_false` may be used to convert the return value to `bool`. 1623 | 1624 | - Examples: 1625 | 1626 | ```{Rcpp logical_any} 1627 | NumericVector A = NumericVector::create(1.0, 2.0, 3.0, 4.0); 1628 | 1629 | Rcout 1630 | << std::boolalpha 1631 | << "any(A > 3): " << is_true(any(A > 3)) << "\n" 1632 | << "any(A > 4): " << is_true(any(A > 4)) << "\n" 1633 | << "any(is_na(A)): " << is_true(any(is_na(A))) 1634 | << "\n\n"; 1635 | // Output: 1636 | // any(x > 3): true 1637 | // any(x > 4): false 1638 | // any(is_na(x)): false 1639 | 1640 | NumericMatrix B(2, 2, A.begin()); 1641 | B[0] = NumericMatrix::get_na(); 1642 | 1643 | Rcout 1644 | << std::boolalpha 1645 | << "any(B > 3): " << is_true(any(B > 3)) << "\n" 1646 | << "any(B > 4): " << is_true(any(B > 4)) << "\n" 1647 | << "any(is_na(B)): " << is_true(any(is_na(B))) 1648 | << "\n\n"; 1649 | // Output: 1650 | // any(B > 3): true 1651 | // any(B > 4): false 1652 | // any(is_na(B)): true 1653 | 1654 | Rcout 1655 | << std::boolalpha 1656 | << "any({false, false, false}): " 1657 | << is_true(any(LogicalVector::create(false, false, false))) << "\n" 1658 | << "any({true, false, false}): " 1659 | << is_true(any(LogicalVector::create(true, false, false))) 1660 | << std::endl; 1661 | // Output: 1662 | // any({false, false, false}): false 1663 | // any({true, false, false}): true 1664 | ``` 1665 | 1666 | - See also: 1667 | - [all](#all) 1668 | - [is_true](#single-logical) 1669 | - [is_false](#single-logical) 1670 | - [is_na](#is-na) 1671 | 1672 | ### Complex Operators {#sugar-complex-ops} 1673 | 1674 | #### Complex Components {#complex-number} 1675 | 1676 | | | | 1677 | |:------------|:------------| 1678 | | **Re( X )** | **Im( X )** | 1679 | 1680 | - Extract the real or imaginary component of a complex number. 1681 | 1682 | - Definition: $$z = x + i y$$, where $x, y \in \mathbb{R}$. 1683 | 1684 | - *X* must be stored within a `Vector` or `Matrix` of type `Complex`. The 1685 | return type is a `NumericVector` regardless of whether a `Vector` or `Matrix` 1686 | is supplied. 1687 | 1688 | - Example: 1689 | 1690 | ```{Rcpp complex_components} 1691 | // Create complex numbers 1692 | Rcomplex x, y; 1693 | 1694 | // Assign real, imaginary values 1695 | x.r = 5.0; x.i = 12.0; 1696 | y.r = 9.2; y.i = -4.0; 1697 | 1698 | // Make a complex vector 1699 | ComplexVector A = ComplexVector::create(x, y); 1700 | // Output: 5+12i 9.2+-4i 1701 | 1702 | NumericVector B = Re(A); 1703 | // Output: 5 9.2 1704 | 1705 | NumericVector C = Im(A); 1706 | // Output: 12 -4 1707 | ``` 1708 | 1709 | 1710 | - See also: 1711 | - [Conj](#complex-conjugate) 1712 | 1713 | #### Mod( X ) {#complex-modulus} 1714 | 1715 | - Compute the modulus of a complex number or the length from the origin to the 1716 | point represented in the complex plane (radius in polar coordinates). 1717 | 1718 | - Definition: $$r = \operatorname{Mod}(z) = \sqrt{x^2 + y^2}$$ 1719 | 1720 | - *X* must be stored within a `Vector` or `Matrix` of type `Complex`. The 1721 | return type is a `NumericVector` regardless of whether a `Vector` or `Matrix` 1722 | is supplied. 1723 | 1724 | - Example: 1725 | 1726 | ```{Rcpp complex_modulus} 1727 | // Create complex numbers 1728 | Rcomplex x, y; 1729 | 1730 | // Assign real, imaginary values 1731 | x.r = 5.0; x.i = 12.0; 1732 | y.r = 9.2; y.i = -4.0; 1733 | 1734 | // Make a complex vector 1735 | ComplexVector A = ComplexVector::create(x, y); 1736 | // Output: 5+12i 9.2+-4i 1737 | 1738 | NumericVector B = Mod(A); 1739 | // Output: 13.00000 10.031949 1740 | ``` 1741 | 1742 | - See also: 1743 | - [Arg](#complex-arg) 1744 | 1745 | #### Arg( X ) {#complex-arg} 1746 | 1747 | - Compute the argument of a complex number or the angle from the positive side 1748 | of the real axis to the line segment connecting the origin and the point in 1749 | the complex plane (theta in polar coordinates). 1750 | 1751 | - Definition: $$\theta = \arctan\left({\frac{y}{x} }\right)$$ 1752 | 1753 | - *X* must be stored within a `Vector` or `Matrix` of type `Complex`. The 1754 | return type is a `NumericVector` regardless of whether a `Vector` or `Matrix` 1755 | is supplied. 1756 | 1757 | - Example: 1758 | 1759 | ```{Rcpp complex_arg} 1760 | // Create complex numbers 1761 | Rcomplex x, y; 1762 | 1763 | // Assign real, imaginary values 1764 | x.r = 5.0; x.i = 12.0; 1765 | y.r = 9.2; y.i = -4.0; 1766 | 1767 | // Make a complex vector 1768 | ComplexVector A = ComplexVector::create(x, y); 1769 | // Output: 5+12i 9.2+-4i 1770 | 1771 | NumericVector B = Arg(A); 1772 | // Output: 1.1760052 -0.4101273 1773 | ``` 1774 | 1775 | - See also: 1776 | - [Mod](#complex-modulus) 1777 | 1778 | #### Conj( X ) {#complex-conjugate} 1779 | 1780 | - Compute the complex conjugate of a complex number or a number with an equivalent 1781 | real component by negated imaginary component. 1782 | 1783 | - *X* must be stored within a `Vector` or `Matrix` of type `Complex`. The 1784 | return type is a `ComplexVector` regardless of whether a `Vector` or `Matrix` 1785 | is supplied. 1786 | 1787 | - Example: 1788 | 1789 | ```{Rcpp complex_conjugate} 1790 | // Create complex numbers 1791 | Rcomplex x, y; 1792 | 1793 | // Assign real, imaginary values 1794 | x.r = 5.0; x.i = 12.0; 1795 | y.r = 9.2; y.i = -4.0; 1796 | 1797 | // Make a complex vector 1798 | ComplexVector A = ComplexVector::create(x, y); 1799 | // Output: 5+12i 9.2+-4i 1800 | 1801 | ComplexVector B = Conj(A); 1802 | // Output: 5-12i 9.2+ 4i 1803 | ``` 1804 | 1805 | - See also: 1806 | - [Re](#complex-number) 1807 | - [Im](#complex-number) 1808 | 1809 | 1810 | ### Data Operations {#sugar-data} 1811 | 1812 | 1813 | #### First or Last Elements {#first-last-elems} 1814 | 1815 | | | | 1816 | |:------------------|:------------------| 1817 | | **head( X , n )** | **tail( X , n )** | 1818 | 1819 | - Obtain the first or last _n_ observations using `head` or `tail`. 1820 | 1821 | - All types of a `Vector` or `Matrix` are supported. 1822 | 1823 | - Example: 1824 | 1825 | ```{Rcpp pop_elements} 1826 | NumericVector A = NumericVector::create(1, 3, 5, 7, 9, 11); 1827 | 1828 | // Retrieve the first two elements 1829 | NumericVector B = head(A, 2); 1830 | // Output: 1 3 1831 | 1832 | // Retrieve the last two elements 1833 | NumericVector C = tail(A, 2); 1834 | // Output: 9 11 1835 | ``` 1836 | 1837 | ---- 1838 | 1839 | #### abs( X ) {#abs} 1840 | 1841 | - Obtain the absolute value of all elements. 1842 | 1843 | - Definition: $$ \left| X \right| = \begin{cases} 1844 | X, &\text{if} X \ge 0 \\ 1845 | -X, &\text{if} X < 0 1846 | \end{cases}$$ 1847 | 1848 | - Supported types to perform the operation are `Numeric` or `Integer` 1849 | of a `Vector` or `Matrix`. 1850 | 1851 | - Example: 1852 | 1853 | ```{Rcpp absolute_val} 1854 | // Sample data 1855 | NumericVector A = NumericVector::create(-2.8, 5.3, 7, -4, 0); 1856 | 1857 | NumericVector B = abs(A); 1858 | // Output: 2.8, 5.3, 7, 4, 0 1859 | ``` 1860 | 1861 | ---- 1862 | 1863 | #### sqrt( X ) {#sqrt} 1864 | 1865 | - Compute the square root of all elements. 1866 | 1867 | - Definition: $$ \sqrt{X} = X^{1/2}$$ 1868 | 1869 | - Supported types to perform the operation are `Numeric`, `Integer`, or `Complex` 1870 | of a `Vector` or `Matrix`. 1871 | 1872 | - Example: 1873 | 1874 | ```{Rcpp sqrt_val} 1875 | // Sample data 1876 | NumericVector A = NumericVector::create(0.0, 1.0, 2.5, 5.0, 9.0); 1877 | 1878 | NumericVector B = sqrt(A); 1879 | // Output: 0 1 1.58114 2.23607 3 1880 | ``` 1881 | 1882 | ---- 1883 | 1884 | #### pow( X , n) {#pow} 1885 | 1886 | - Obtain the power of the _i_^th^ element raised to the _n_ power. 1887 | 1888 | - Definition: $$ Y = X^{n}$$ 1889 | 1890 | - Supported types to perform the operation are `Numeric` or `Integer` 1891 | of a `Vector` or `Matrix`. 1892 | 1893 | - **Caveat:** Only _X_ is able to be vectorized. The value of _n_ must be 1894 | a scalar of `int` or `double` type. 1895 | 1896 | - Example: 1897 | 1898 | ```{Rcpp pow_val} 1899 | // Sample data 1900 | NumericVector A = NumericVector::create(0.0, 1.0, 2.5, 5.0, 9.0); 1901 | 1902 | NumericVector B = pow( A , 3 ); 1903 | // Output: 0 1 15.625 125 729 1904 | ``` 1905 | 1906 | ---- 1907 | 1908 | #### sum( X ) {#sum} 1909 | 1910 | - Calculate the overall summation of all elements. 1911 | 1912 | - Definition: $$Y = \sum\limits_{i = 1}^n { {X_i} } $$ 1913 | 1914 | - Supported types to perform the operation are `Numeric` or `Integer` 1915 | of a `Vector` or `Matrix`. 1916 | 1917 | - Example: 1918 | 1919 | ```{Rcpp sum_val} 1920 | // Sample data 1921 | NumericVector A = NumericVector::create(3.2, 8.1, 9.5, 8.6, 5.7); 1922 | 1923 | double val_summed = sum(A); 1924 | // Output: 35.1 1925 | ``` 1926 | 1927 | - See also: 1928 | - [`rowSums` / `colSums`](#matrix-sum) 1929 | 1930 | ---- 1931 | 1932 | #### sign( X ) {#sign} 1933 | 1934 | - Determine the sign of a number or whether a number is positive, negative, or 1935 | zero. 1936 | 1937 | - Definition: $$\operatorname{sgn} \left( X \right) = \begin{cases} 1938 | -1, &\text{if} x < 0 \\ 1939 | 0, &\text{if} x = 0 \\ 1940 | 1, &\text{if} x > 0 1941 | \end{cases}$$ 1942 | 1943 | - Supported types are `Numeric` or `Integer` of a `Vector` or `Matrix`. 1944 | 1945 | - Example: 1946 | 1947 | ```{Rcpp sign_val} 1948 | // Create some sample data 1949 | NumericVector A = NumericVector::create(-1, 0, 1, -3.4, 42); 1950 | 1951 | // --- Obtain values of the sign 1952 | 1953 | NumericVector B = sign(A); 1954 | // Output: -1 0 1 -1 1 1955 | ``` 1956 | 1957 | ---- 1958 | 1959 | #### diff( X ) {#diff} 1960 | 1961 | - Obtain the difference between sucessive `Vector` elements by 1962 | $(i+1)$^th^ and the _i_-^th^ element. 1963 | 1964 | - Definition: $$ \nabla {X_i} = {X_{i + 1} } - {X_i} $$ 1965 | 1966 | - Supported types are `Numeric` or `Integer` of a `Vector` or `Matrix`. 1967 | 1968 | - Example: 1969 | 1970 | ```{Rcpp diff_val} 1971 | // Create some sample data 1972 | NumericVector A = NumericVector::create(-2, 0, 0.5, -1, 2.5, 4.75); 1973 | 1974 | // --- Obtain difference 1975 | 1976 | NumericVector B = diff(A); 1977 | // Output: 2.00 0.50 -1.50 3.50 2.25 1978 | ``` 1979 | 1980 | ---- 1981 | 1982 | #### Cumulative Arithmetic {#carth} 1983 | 1984 | | | | 1985 | |:----------------|:-----------------| 1986 | | **cumsum( X )** | **cumprod( X )** | 1987 | 1988 | - Calculates the cumulative sum (`cumsum`) or cumulative product (`cumprod`) 1989 | of a `Vector` or `Matrix` *X*. 1990 | 1991 | - If an `NA` value is encountered, it will be propagated throughout the 1992 | remaining elements in the result vector. 1993 | 1994 | - For `cumsum`, *X* should be an `Integer` or `Numeric` `Vector` or `Matrix`. 1995 | 1996 | - For `cumprod`, *X* should be an `Integer`, `Numeric`, or `Complex` `Vector` 1997 | or `Matrix`. 1998 | 1999 | - In either case, the return type is a `Vector` of the same underlying `SEXPTYPE` 2000 | as the input. 2001 | 2002 | - Caveat: at the time of writing (Rcpp version 0.12.11), not all Sugar expressions 2003 | are directly compatible with `Vector::operator=`, as many of these functions 2004 | return intermediate template classes which require an explicit conversion to 2005 | `Vector`, rather than directly returning a `Vector`. In such cases the user 2006 | may need to "help" the compiler with the conversion by 2007 | 2008 | - Constructing a `Vector` from the result, and assigning that to the 2009 | target `Vector`; or 2010 | - Calling an explicit conversion member function of the Sugar class, if 2011 | such a function exists. 2012 | 2013 | See the examples below for a demonstration. 2014 | 2015 | - Examples: 2016 | 2017 | ```{Rcpp cumarith} 2018 | NumericVector x = NumericVector::create(1, 2, 3, 4, 5); 2019 | NumericVector cs = cumsum(x), cp = cumprod(x); 2020 | 2021 | Rcout 2022 | << "cumsum(x): \n" << cs << "\n\n" 2023 | << "cumprod(x): \n" << cp << "\n\n"; 2024 | // Output: 2025 | // cumsum(x): 2026 | // 1 3 6 10 15 2027 | // 2028 | // cumprod(x): 2029 | // 1 2 6 24 120 2030 | 2031 | x[3] = NumericVector::get_na(); 2032 | 2033 | cs = cumsum(x).get(); 2034 | cp = cumprod(x).get(); 2035 | 2036 | // These print as `nan`, but are actually `NA` values 2037 | Rcout 2038 | << "cumsum(x): \n" << cs << "\n\n" 2039 | << "cumprod(x): \n" << cp 2040 | << std::endl; 2041 | // Output: 2042 | // cumsum(x): 2043 | // 1 3 6 nan nan 2044 | // 2045 | // cumprod(x): 2046 | // 1 2 6 nan nan 2047 | 2048 | // As noted above: 2049 | NumericVector y = NumericVector::create(1, 2, 3, 4, 5); 2050 | 2051 | NumericVector cs = cumsum(y); // OK, calls copy *constructor*, not 2052 | // copy assignment operator 2053 | 2054 | // cs = cumsum(y); compiler error: no viable conversion from 2055 | // 'const Rcpp::sugar::Cumsum<14, true, Rcpp::Vector<14, PreserveStorage> >' 2056 | // to 'SEXP' (aka 'SEXPREC *') 2057 | 2058 | cs = cumsum(y).get(); // OK, `get()` returns a VectorBase, which is 2059 | // assignable to Vector 2060 | 2061 | cs = NumericVector(cumsum(y)); // OK, but requires an additional Vector 2062 | // to be created 2063 | ``` 2064 | 2065 | ---- 2066 | 2067 | #### Cumulative Extremum {#cext} 2068 | 2069 | | | | 2070 | |:----------------|:-----------------| 2071 | | **cummax( X )** | **cummin( X )** | 2072 | 2073 | 2074 | - Calculates the cumulative maximum (`cummax`) or cumulative minimum (`cummin`) 2075 | of a `Vector` or `Matrix` *X*. 2076 | 2077 | - If an `NA` value is encountered, it will be propagated throughout the 2078 | remaining elements in the result vector. 2079 | 2080 | - Supported types are `Integer` or `Numeric` of a `Vector` or `Matrix`. 2081 | 2082 | - Caveat: at the time of writing (Rcpp version 0.12.11), not all Sugar expressions 2083 | are directly compatible with `Vector::operator=`, as many of these functions 2084 | return intermediate template classes which require an explicit conversion to 2085 | `Vector`, rather than directly returning a `Vector`. In such cases the user 2086 | may need to "help" the compiler with the conversion by 2087 | 2088 | - Constructing a `Vector` from the result, and assigning that to the 2089 | target `Vector`; or 2090 | - Calling an explicit conversion member function of the Sugar class, if 2091 | such a function exists. 2092 | 2093 | See the examples below for a demonstration. 2094 | 2095 | - Examples: 2096 | 2097 | ```{Rcpp cumextrema} 2098 | NumericVector x = NumericVector::create(1, -2, 5, 10, -4); 2099 | NumericVector cmax = cummax(x), cmin = cummin(x); 2100 | 2101 | Rcout 2102 | << "cummax(x): \n" << cmax << "\n\n" 2103 | << "cummin(x): \n" << cmin << "\n\n"; 2104 | // Output: 2105 | // cummax(x): 2106 | // 1 1 5 10 10 2107 | // 2108 | // cummin(x): 2109 | // 1 -2 -2 -2 -4 2110 | 2111 | x[3] = NumericVector::get_na(); 2112 | 2113 | cmax = cummax(x).get(); 2114 | cmin = cummin(x).get(); 2115 | 2116 | // These print as `nan`, but are actually `NA` values 2117 | Rcout 2118 | << "cummax(x): \n" << cmax << "\n\n" 2119 | << "cummin(x): \n" << cmin 2120 | << std::endl; 2121 | // Output: 2122 | // cummax(x): 2123 | // 1 1 5 nan nan 2124 | // 2125 | // cummin(x): 2126 | // 1 -2 -2 nan nan 2127 | 2128 | // As noted above: 2129 | NumericVector y = NumericVector::create(1, 2, 3, 4, 5); 2130 | 2131 | NumericVector cmax = cummax(y); // OK, calls copy *constructor*, not 2132 | // copy assignment operator 2133 | 2134 | // cmax = cummax(y); compiler error: no viable conversion from 2135 | // 'const Rcpp::sugar::cummax<14, true, Rcpp::Vector<14, PreserveStorage> >' 2136 | // to 'SEXP' (aka 'SEXPREC *') 2137 | 2138 | cmax = cummax(y).get(); // OK, `get()` returns a VectorBase, which is 2139 | // assignable to Vector 2140 | 2141 | cmax = NumericVector(cummax(y)); // OK, but requires an additional Vector 2142 | // to be created 2143 | ``` 2144 | 2145 | 2146 | ---- 2147 | 2148 | 2149 | #### trigonometric element-wise functions {#trig} 2150 | 2151 | | | | | 2152 | |:-------------|:---------------|:--------------| 2153 | | **sin( X )** | **asin( X )** | **sinh( X )** | 2154 | | **cos( X )** | **acos( X )** | **cosh( X )** | 2155 | | **tan( X )** | **atan( X )** | **tanh( X )** | 2156 | 2157 | - Compute the trigonometric value for each element in a given structure. 2158 | 2159 | - Usage: 2160 | - `vector_type Y = func(X)` 2161 | - `X` and `Y` must be of the same `vector_type`/`matrix_type`. 2162 | - where `func` is one of the following trigonmetric functions: 2163 | - sin family: `sin(X)`, `asin(X)`, `sinh(X)` 2164 | - cos family: `cos(X)`, `acos(X)`, `cosh(X)` 2165 | - tan family: `tan(X)`, `atan(X)`, `tanh(X)` 2166 | 2167 | - Supported types are `Integer`, `Numeric`, or `Complex` of a `Vector` or `Matrix`. 2168 | 2169 | - Examples: 2170 | 2171 | ```{Rcpp rcpp_trig_funcs} 2172 | // Generate Values 2173 | NumericVector X = rnorm(10); 2174 | 2175 | // Compute trigonometric values 2176 | NumericVector Y = cos(X); 2177 | NumericVector Y2 = acos(X); 2178 | NumericVector Y3 = cosh(X); 2179 | ``` 2180 | 2181 | --- 2182 | 2183 | #### Logarithms and Exponentials {#logexp} 2184 | 2185 | | | | | 2186 | |:-------------|:---------------|:---------------| 2187 | | **log( X )** | **log10( X )** | **log1p( X )** | 2188 | | **exp( X )** | **expm1( X )** | | 2189 | 2190 | - Apply a function to each element 2191 | 2192 | - Usage: 2193 | - `vector_type Y = func(X)` 2194 | - `X` and `Y` must be of the same `vector_type`/`matrix_type`. 2195 | 2196 | - Traditional use case: 2197 | - `log( X )` computes the natural logarithm sometimes representated as $\ln(X)$ 2198 | - `log10( X )` computes the base 10 logarithm. 2199 | - `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!} } } $$ 2200 | 2201 | - Special use cases: 2202 | - `log1p( X )` computes $\log( 1 + X )$ accurately for $\left|X\right| << 1$. 2203 | - `expm1( X )` computes $\exp( X ) - 1$ accurately for $\left|X\right| << 1$. 2204 | 2205 | - Examples: 2206 | 2207 | ```{Rcpp rcpp_logs_and_exp} 2208 | // Create some sample data 2209 | NumericVector A = NumericVector::create(-1, 0, 1, 2.3); 2210 | 2211 | // --- Log and Exp Functions 2212 | 2213 | // Obtain the exponential 2214 | 2215 | NumericVector B = exp(A); 2216 | // Output: 0.3678794 1.0000000 2.7182818 9.9741825 2217 | 2218 | // Obtain the natural log, which should recover the initial values 2219 | 2220 | NumericVector C = log(B); 2221 | // Output: -1.0 0.0 1.0 2.3 2222 | 2223 | // --- Compare implementations of log1p and expm1 vs. generic 2224 | 2225 | // Create input vector 2226 | NumericVector D = no_init(10); 2227 | 2228 | // Fill the vector 2229 | for(int i = 0; i < D.length(); ++i){ 2230 | D[i] = std::pow(10.0, -1.0*( 1.0 + 2.0*(i+1.0) ) ); 2231 | } 2232 | 2233 | // Compute values according to definition 2234 | NumericVector E = log(1 + D), F = log1p(D), G = exp(D)-1, H = expm1(D); 2235 | 2236 | // Bound values together 2237 | NumericMatrix I = cbind(D, E, F, G, H); 2238 | 2239 | // Label columns 2240 | colnames(I) = CharacterVector::create("X", "log(1+X)","log1p(X)", "exp(X)+1", "expm1(X)"); 2241 | 2242 | // Output: 2243 | // X log(1+X) log1p(X) exp(X)+1 expm1(X) 2244 | // [1,] 1e-03 9.995003e-04 9.995003e-04 1.000500e-03 1.000500e-03 2245 | // [2,] 1e-05 9.999950e-06 9.999950e-06 1.000005e-05 1.000005e-05 2246 | // [3,] 1e-07 1.000000e-07 1.000000e-07 1.000000e-07 1.000000e-07 2247 | // [4,] 1e-09 1.000000e-09 1.000000e-09 1.000000e-09 1.000000e-09 2248 | // [5,] 1e-11 1.000000e-11 1.000000e-11 1.000000e-11 1.000000e-11 2249 | // [6,] 1e-13 9.992007e-14 1.000000e-13 9.992007e-14 1.000000e-13 2250 | // [7,] 1e-15 1.110223e-15 1.000000e-15 1.110223e-15 1.000000e-15 2251 | // [8,] 1e-17 0.000000e+00 1.000000e-17 0.000000e+00 1.000000e-17 2252 | // [9,] 1e-19 0.000000e+00 1.000000e-19 0.000000e+00 1.000000e-19 2253 | // [10,] 1e-21 0.000000e+00 1.000000e-21 0.000000e+00 1.000000e-21 2254 | ``` 2255 | 2256 | --- 2257 | 2258 | #### sample {#sample} 2259 | 2260 | | | 2261 | |:-----------------------------------------------| 2262 | | **sample( n , size , replace , probs )** | 2263 | | **sample( X , size , replace , probs )** | 2264 | 2265 | - Obtain a random sampling of elements from either a positive number of elements 2266 | ranging from 1 to _n_ or data contained with _X_. 2267 | 2268 | - All types are supported of a `Vector` or `Matrix`. 2269 | 2270 | - The parameters available for `sample` are defined as: 2271 | - `size`, the number of items to sample 2272 | - `replace = false`, allow replacement or elements to be added back in if picked. 2273 | - `probs = R_NilValue`, vector containing probability weights 2274 | 2275 | - Examples: 2276 | 2277 | ```{Rcpp sugar_sample} 2278 | /*** R 2279 | # in R set a seed for reproducibility 2280 | set.seed(111) 2281 | */ 2282 | 2283 | // Create some sample data 2284 | NumericVector A = NumericVector::create(-3.5, 2, 2.2, 0.1, -.4, -1, 4.75); 2285 | 2286 | // --- Sampling approaches 2287 | 2288 | // Using a positive number 2289 | IntegerVector C = sample(10, 4); 2290 | // Output: 6 4 9 1 2291 | 2292 | // Sample from a vector 2293 | NumericVector B = sample(A, 3); 2294 | // Output: -0.4 4.75 2 2295 | ``` 2296 | --- 2297 | 2298 | ### Rounding of Numbers {#sugar-rounding} 2299 | 2300 | 2301 | #### Ceiling {#ceil} 2302 | 2303 | | | | 2304 | |:-----------------------|:------------------------| 2305 | | **ceiling( X )** | **ceil( X )** | 2306 | 2307 | - Compute the smallest integer value not less than the corresponding element of X. 2308 | 2309 | - Definition: $$\left\lceil X \right\rceil = \min \left[ {n \in \mathbb{Z}|n \ge X} \right]$$ 2310 | 2311 | - Supported types are `Numeric` or `Integer` of a `Vector` or `Matrix`. 2312 | 2313 | - **Note:** `ceil` is a mapping to `ceiling`. 2314 | 2315 | - Examples: 2316 | 2317 | ```{Rcpp ceil_val} 2318 | // Create some sample data 2319 | NumericVector A = NumericVector::create(-3.5, 2, 2.2, 0.1, -.4, -1, 4.75); 2320 | 2321 | // --- Obtain the ceiling 2322 | 2323 | NumericVector B = ceiling(A); 2324 | // Output: -3 2 3 1 0 -1 5 2325 | 2326 | // Same result 2327 | NumericVector C = ceil(A); 2328 | // Output: -3 2 3 1 0 -1 5 2329 | ``` 2330 | 2331 | ---- 2332 | 2333 | #### floor( X ) {#floor} 2334 | 2335 | - Compute the largest integer value not greater than the corresponding element of X. 2336 | 2337 | - Definition: $$\left\lfloor X \right\rfloor = \max \left[ {n \in \mathbb{Z}|n \le X} \right]$$ 2338 | 2339 | - Supported types are `Numeric` or `Integer` of a `Vector` or `Matrix`. 2340 | 2341 | - Examples: 2342 | 2343 | ```{Rcpp floor_val} 2344 | // Create some sample data 2345 | NumericVector A = NumericVector::create(-3.5, 2, 2.2, 0.1, -.4, -1, 4.75); 2346 | 2347 | // --- Obtain the floor 2348 | 2349 | NumericVector B = floor(A); 2350 | // Output: -4 2 2 0 -1 -1 4 2351 | ``` 2352 | 2353 | ---- 2354 | 2355 | #### trunc( X ) {#trunc} 2356 | 2357 | - Obtain the integers formed by truncating the values in X toward 0. 2358 | 2359 | - Definition: $$\operatorname{trunc}\left( X \right) = \begin{cases} 2360 | \left\lfloor X \right\rfloor, &\text{if} X > 0 \\ 2361 | \left\lceil X \right\rceil, &\text{if} X < 0 2362 | \end{cases} 2363 | $$ 2364 | 2365 | - Supported types are `Numeric` or `Integer` of a `Vector` or `Matrix`. 2366 | 2367 | - Examples: 2368 | 2369 | ```{Rcpp trunc_val} 2370 | // Create some sample data 2371 | NumericVector A = NumericVector::create(-3.5, 2, 2.2, 0.1, -.4, -1, 4.75); 2372 | 2373 | // --- Obtain the truncated value 2374 | 2375 | NumericVector B = trunc(A); 2376 | // Output: -3 2 2 0 0 -1 4 2377 | ``` 2378 | 2379 | - See also: 2380 | - [`ceil`](#ceil) 2381 | - [`floor`](#floor) 2382 | - [Truncation](https://en.wikipedia.org/wiki/Truncation) 2383 | 2384 | ---- 2385 | 2386 | #### round( X , digits ) {#round} 2387 | 2388 | - Obtain a rounded number to specified number of decimal places. 2389 | 2390 | - There is _no_ default value for `digits`. This parameter _must_ be specified 2391 | with an `int`. 2392 | 2393 | - Supported types are `Numeric` or `Integer` of a `Vector` or `Matrix`. 2394 | 2395 | - Examples: 2396 | 2397 | ```{Rcpp round_val} 2398 | // Create some sample data 2399 | NumericVector A = NumericVector::create(-3.5, 2, 2.2, 0.1, -.4, -1, 4.75); 2400 | 2401 | // --- Obtain the round values 2402 | 2403 | // Default rounds to no decimal places 2404 | NumericVector B = round(A, 0); 2405 | // Output: -4 2 2 0 0 -1 5 2406 | 2407 | NumericVector C = round(A, 1); 2408 | // Output: -3.5 2.0 2.2 0.1 -0.4 -1.0 4.8 2409 | ``` 2410 | 2411 | ---- 2412 | 2413 | #### signif( X, digits ) {#signif} 2414 | 2415 | - Round the number to the appropriate number of significant digits. 2416 | 2417 | - There is _no_ default value for `digits`. This parameter _must_ be specified 2418 | with an `int`. 2419 | 2420 | - Supported types are `Numeric` or `Integer` of a `Vector` or `Matrix`. 2421 | 2422 | - Examples: 2423 | 2424 | ```{Rcpp signif_val} 2425 | // Create some sample data 2426 | NumericVector A = NumericVector::create(11252, 59622, 764, 94512, 4121.5); 2427 | 2428 | // --- Obtain the significant digits 2429 | 2430 | // Default rounds to no decimal places 2431 | NumericVector B = signif(A, 2); 2432 | // Output: 11000 60000 760 95000 4100 2433 | 2434 | NumericVector C = round(A, 3); 2435 | // Output: 11300 59600 764 94500 4120 2436 | ``` 2437 | 2438 | --- 2439 | 2440 | ### Finite, Infinite, Missingness, and NaN Detection {#sugar-nan} 2441 | 2442 | - Finite numerical representations take the form of base 10 numbers like 1, 2, 2443 | ..., 42, and so on. These values are able to be operated upon such that 2444 | a collection of numerical values can provide a statistical summary. 2445 | However, when working with values that hold special meanings the representation 2446 | is not necessarily ideal. Therefore, a set of tools exists to detect when 2447 | values with special meanings exist. 2448 | 2449 | - From [Kevin Ushey's post on StackOverflow](http://stackoverflow.com/questions/26241085/rcpp-function-check-if-missing-value/26262984#26262984), 2450 | we have a set of truth tables or an indicator of whether the value is detected 2451 | by a given function, which covers the R interpreter, Rcpp, and R/C API. Note, 2452 | Rcpp by default follows how R interpreter has crafted the methods. 2453 | 2454 | - R interpreter: 2455 | 2456 | | Function | `NaN` | `NA` | 2457 | |:-----------|:-----:|:----:| 2458 | | `is.na` | `T` | `T` | 2459 | | `is.nan` | `T` | `F` | 2460 | 2461 | - Rcpp: 2462 | 2463 | | Function | `NaN` | `NA` | 2464 | |:---------------|:-----:|:----:| 2465 | | `Rcpp::is_na` | `T` | `T` | 2466 | | `Rcpp::is_nan` | `T` | `F` | 2467 | 2468 | - R/C API: 2469 | 2470 | | Function | `NaN` | `NA`| 2471 | |:-----------|:-----:|:---:| 2472 | | `ISNA` | `F` | `T` | 2473 | | `R_IsNA` | `F` | `T` | 2474 | | `ISNAN` | `T` | `T` | 2475 | | `R_IsNaN` | `T` | `F` | 2476 | 2477 | - Note: The R/C API is highly inconsistent when detecting values. 2478 | 2479 | #### Setting Infinite, Missingness, and NaN Values {#nan-constants} 2480 | 2481 | - To indicate missingness or `NA` values, the following pre-defined constants 2482 | have been made available for specific Rcpp data types: 2483 | 2484 | | Rcpp Data Type | Rcpp Value | Description | 2485 | |:------------------------:|:-----------------:|:------------------------:| 2486 | | Numeric | `NA_REAL` | Numeric Missing Value | 2487 | | Integer | `NA_INTEGER` | Integer Missing Value | 2488 | | Logical | `NA_LOGICAL` | Logical Missing Value | 2489 | | Character | `NA_STRING` | String Missing Value | 2490 | 2491 | 2492 | - To set a missing value type for any type of `Vector` or `Matrix` regardless of 2493 | whether a pre-defined exists, one can use the static member `::get_na()`, e.g. 2494 | `ComplexVector::get_na()` creates an `NA` value for a complex vector. 2495 | 2496 | - The `Numeric` and `double` data types also support the following special 2497 | constant values: 2498 | 2499 | | Rcpp Value | Value | Description | 2500 | |:---------------:|:----------:|:------------------:| 2501 | | `R_PosInf` | `Inf` | Positive Infinity | 2502 | | `R_NegInf` | `-Inf` | Negative Infinity | 2503 | | `R_NaN` | `NaN` | Not a Number | 2504 | 2505 | - Note: Understanding the breakdown of the values is important as it relates to 2506 | detecting whether an element is [finite](#finite), 2507 | [missing or computationally problematic](#missingness). 2508 | 2509 | - Examples 2510 | 2511 | ```{Rcpp sample_nas} 2512 | // Create an NA value for each type 2513 | NumericVector A = NumericVector::create(NA_REAL); 2514 | IntegerVector B = IntegerVector::create(NA_INTEGER); 2515 | LogicalVector C = LogicalVector::create(NA_LOGICAL); 2516 | CharacterVector D = CharacterVector::create(NA_STRING); 2517 | // Output: NA 2518 | 2519 | // Group all of the above together 2520 | List E = List::create(A, B, C, D); 2521 | ``` 2522 | 2523 | - See also: 2524 | - [R Extensions: Missing and IEEE values](https://cran.r-project.org/doc/manuals/r-devel/R-exts.html#Missing-and-IEEE-values) 2525 | - [R Extensions: Missing and special values](https://cran.r-project.org/doc/manuals/r-devel/R-exts.html#Missing-and-special-values) 2526 | 2527 | --- 2528 | 2529 | #### Finiteness {#finite} 2530 | 2531 | | | | 2532 | |:-------------------|:---------------------| 2533 | | **is_finite( X )** | **is_infinite( X )** | 2534 | 2535 | - Determines whether each element of _X_ are finite (`is_finite`) or infinite (`is_infinite`). 2536 | 2537 | - Support exisits for only the `Numeric` type of a `Vector` or `Matrix`. 2538 | 2539 | - **Note:** Infinite detection is only applicable to `Numeric` types as these 2540 | values are only defined for `double` types. 2541 | 2542 | - **Caveat:** Not a Number is _not_ considered to be a finite nor infinite 2543 | value. If this value exists within the object, it must be detected with 2544 | `is_nan` or `is_na`. 2545 | 2546 | - Examples: 2547 | 2548 | ```{Rcpp is_infinite_v_finite} 2549 | NumericVector A = NumericVector::create(R_NegInf, -5, 0, 12, R_PosInf, 42, R_NaN) ; 2550 | 2551 | LogicalVector B = is_finite( A ); 2552 | // Output: FALSE, TRUE, TRUE, TRUE, FALSE, TRUE, FALSE 2553 | 2554 | LogicalVector C = is_infinite( A ); 2555 | // Output: TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE 2556 | ``` 2557 | 2558 | - See also: 2559 | - [`is_na` / `is_nan`](#missingness) 2560 | 2561 | --- 2562 | 2563 | #### Missing Values and NaN Detection {#missingness} 2564 | 2565 | | | | 2566 | |:-------------------|:---------------------| 2567 | | **is_na( X )** | **is_nan( X )** | 2568 | 2569 | 2570 | - Determines the missing values (`is_na`) or not a number (`is_nan`). 2571 | 2572 | - All types are supported of a `Vector` or `Matrix`. 2573 | 2574 | - Note: The difference between the two functions is explained by in the truth 2575 | table 2576 | 2577 | 2578 | | Function | `NaN` | `NA` | 2579 | |:---------------|:-----:|:----:| 2580 | | `Rcpp::is_na` | `T` | `T` | 2581 | | `Rcpp::is_nan` | `T` | `F` | 2582 | 2583 | 2584 | - Examples: 2585 | 2586 | ```{Rcpp is_na_v_nan} 2587 | NumericVector X = NumericVector::create(R_NaN, 1, NA_REAL, 3 ) ; 2588 | 2589 | LogicalVector result_na = is_na( X ); 2590 | // Output: TRUE, FALSE, TRUE, FALSE 2591 | 2592 | LogicalVector result_nan = is_nan( X ); 2593 | // Output: TRUE, FALSE, FALSE, FALSE 2594 | ``` 2595 | 2596 | --- 2597 | 2598 | ### na_omit( X ) {#na-omit} 2599 | 2600 | - Removes values that are either `NA` or `NaN`. 2601 | 2602 | - All types are supported of a `Vector` or `Matrix`. 2603 | 2604 | - Example: 2605 | 2606 | ```{Rcpp na_omit} 2607 | // Create some sample data 2608 | NumericVector A = NumericVector::create(R_NaN, 1, NA_REAL, 3 , NA_REAL) ; 2609 | 2610 | // Remove NA and NaN Values 2611 | NumericVector B = na_omit(A); 2612 | // Output: 1 3 2613 | ``` 2614 | 2615 | --- 2616 | 2617 | ### noNA( X ) {#nona} 2618 | 2619 | - Assert the object is `NA`-free to avoid checking whether each value is not 2620 | missing. 2621 | 2622 | - All types are supported of a `Vector` or `Matrix`. 2623 | 2624 | - **Warning:** Using `noNA` with a `Matrix` defaults the underlying class 2625 | from a `Matrix` to `VectorBase`! Thus, the matrix dimensional information is 2626 | _lost_. 2627 | 2628 | - Example: 2629 | 2630 | ```{Rcpp noNA} 2631 | // Create some sample data 2632 | NumericVector A = NumericVector::create(1, 2, 3, 4) ; 2633 | 2634 | // Assert vector is NA-free 2635 | NumericVector B = noNA(A); 2636 | // Output: 1 2 3 4 2637 | ``` 2638 | 2639 | - See also: 2640 | - [StackOverflow: Nathan Russell's Remarks on `noNA`](http://stackoverflow.com/a/41874411/1345455) 2641 | 2642 | --- 2643 | 2644 | ### The Apply Family {#sugar-apply} 2645 | 2646 | 2647 | #### sapply {#sapply} 2648 | 2649 | - Apply a _C++_ function or functor to each element of an object and receive 2650 | a `Vector` back. 2651 | 2652 | - The return type is automatically detected by the supplied _C++_ 2653 | function or functor of the `Vector` class. 2654 | 2655 | - All types are supported of a `Vector` or `Matrix`. 2656 | 2657 | ```{Rcpp sapply_example} 2658 | 2659 | // --- C++ Function Approach 2660 | template 2661 | T square( const T& x){ 2662 | return x * x ; 2663 | } 2664 | 2665 | IntegerVector test_sapply_function() { 2666 | // Create sample data 2667 | IntegerVector A = seq_len(10); 2668 | 2669 | // Call C++ Function 2670 | IntegerVector B = sapply(A, square); 2671 | 2672 | return B; 2673 | } 2674 | 2675 | test_sapply_function(); 2676 | // Output: 1 4 9 16 25 36 49 64 81 100 2677 | 2678 | 2679 | // --- C++ Functor Approach 2680 | template 2681 | struct square : std::unary_function { 2682 | T operator()(const T& x) const { return x * x; } 2683 | }; 2684 | // std::unary_function is deprecated in C++11 2685 | 2686 | IntegerVector test_sapply_functor() { 2687 | // Create sample data 2688 | IntegerVector A = seq_len(10); 2689 | 2690 | // Call C++ Function 2691 | IntegerVector C = sapply(A, square()); 2692 | 2693 | return C; 2694 | } 2695 | 2696 | test_sapply_functor(); 2697 | // Output: 1 4 9 16 25 36 49 64 81 100 2698 | ``` 2699 | --- 2700 | 2701 | #### lapply {#lapply} 2702 | 2703 | - Apply a _C++_ function or functor to each element of an object and receive 2704 | a `List` back. 2705 | 2706 | - All types are supported of a `Vector` or `Matrix`. 2707 | 2708 | ```{Rcpp lapply_example} 2709 | // --- C++ Function Approach 2710 | template 2711 | T square( const T& x){ 2712 | return x * x ; 2713 | } 2714 | 2715 | List test_lapply_function() { 2716 | // Create sample data 2717 | IntegerVector A = seq_len(3); 2718 | 2719 | // Call C++ Function 2720 | List B = sapply(A, square); 2721 | 2722 | return B; 2723 | } 2724 | 2725 | test_lapply_function(); 2726 | // Output: 2727 | // [[1]] 2728 | // [1] 1 2729 | // [[2]] 2730 | // [1] 4 2731 | // [[3]] 2732 | // [1] 9 2733 | 2734 | // --- C++ Functor Approach 2735 | template 2736 | struct square : std::unary_function { 2737 | T operator()(const T& x) const { return x * x; } 2738 | }; 2739 | // std::unary_function is deprecated in C++11 2740 | 2741 | IntegerVector test_lapply_functor() { 2742 | // Create sample data 2743 | IntegerVector A = seq_len(3); 2744 | 2745 | // Call C++ Function 2746 | List C = lapply(A, square()); 2747 | 2748 | return C; 2749 | } 2750 | 2751 | test_lapply_functor(); 2752 | // Output: 2753 | // [[1]] 2754 | // [1] 1 2755 | // [[2]] 2756 | // [1] 4 2757 | // [[3]] 2758 | // [1] 9 2759 | ``` 2760 | 2761 | --- 2762 | 2763 | #### mapply {#mapply} 2764 | 2765 | - Apply a _C++_ function or functor on up to three input objects and receive 2766 | a `Vector`. 2767 | 2768 | - The return type is automatically detected by the supplied _C++_ 2769 | function or functor of the `Vector` class. 2770 | 2771 | - All types are supported of a `Vector` or `Matrix`. 2772 | 2773 | - Example: 2774 | 2775 | ```{Rcpp mapply_example} 2776 | // --- C++ Function Example 2777 | template 2778 | T sum_val(T x, T y, T z) { 2779 | return x + y + z ; 2780 | } 2781 | 2782 | // Sample Data 2783 | NumericVector A = NumericVector::create(1, 2, 3); 2784 | NumericVector B = NumericVector::create(2, 3, 4); 2785 | NumericVector C = NumericVector::create(3, 4, 5); 2786 | 2787 | NumericVector D = mapply(A, B, C, sum_val); 2788 | // Output: 6 9 12 2789 | ``` 2790 | 2791 | - See also: 2792 | - [`sapply`](#sapply) 2793 | 2794 | --- 2795 | 2796 | ### Special Functions of Mathematics {#sugar-special-math} 2797 | 2798 | #### Beta {#beta} 2799 | 2800 | | | | 2801 | |:-----------------|:------------------| 2802 | | **beta( A, B )** | **lbeta( A, B )** | 2803 | 2804 | 2805 | - Compute value of the beta function, $B \left(a,b\right)$, and the natural 2806 | logarithm of the beta function, 2807 | $\log \left( {B \left(a,b\right)} \right)$. 2808 | 2809 | - **Definition:** 2810 | 2811 | $$\begin{aligned} 2812 | B\left( {a,b} \right) &= \frac{ {\Gamma \left( a \right)\Gamma \left( b \right)} }{ {\Gamma \left( {a + b} \right)} } \\ 2813 | & = \int\limits_0^1 { {t^{\left( {a - 1} \right)} }{ {\left( {1 - t} \right)}^{\left( {b - 1} \right)} }dt} \\ 2814 | \log \left( { B\left( {a,b} \right) } \right) &= \log \left( { \int\limits_0^1 { {t^{\left( {a - 1} \right)} }{ {\left( {1 - t} \right)}^{\left( {b - 1} \right)} }dt} } \right) 2815 | \end{aligned}$$ 2816 | 2817 | - Supported types are `Integer` or `Numeric` of a `Vector` or `Matrix`. 2818 | 2819 | - Examples: 2820 | 2821 | ```{Rcpp} 2822 | // Sample Data 2823 | NumericVector A = NumericVector::create(10, 9, 8, 7, 6); 2824 | NumericVector B = NumericVector::create(5, 4, 3, 2, 1); 2825 | 2826 | // --- Sample Vectorized Calls 2827 | 2828 | NumericVector C = beta(A, B); 2829 | // Output: 9.99001e-005 0.000505051 0.00277778 0.0178571 0.166667 2830 | 2831 | NumericVector D = lbeta(A, B); 2832 | // Output: -9.21134 -7.59085 -5.8861 -4.02535 -1.79176 2833 | 2834 | // --- Optional Scalar 2835 | 2836 | NumericVector E = beta(10, B); 2837 | // Output: 9.99001e-005 0.00034965 0.00151515 0.00909091 0.1 2838 | 2839 | NumericVector F = beta(A, 5); 2840 | // Output: 9.99001e-005 0.0001554 0.000252525 0.0004329 0.000793651 2841 | ``` 2842 | 2843 | --- 2844 | 2845 | #### Gamma {#gamma} 2846 | 2847 | | | | 2848 | |:---------------|:-----------------| 2849 | | **gamma( X )** | **lgamma( X )** | 2850 | 2851 | - Compute value of the gamma function, $\Gamma \left(x\right)$, and the natural 2852 | logarithm of the absolute value of the gamma function, 2853 | $\log \left( {\left| {\Gamma \left( x \right)} \right|} \right)$. 2854 | 2855 | - **Definition:** 2856 | 2857 | $$\begin{aligned} 2858 | \Gamma \left( x \right) &= \int\limits_0^\infty { {t^{\left( {x - 1} \right)} }\exp \left( { - t} \right)dt} \\ 2859 | \log \left( {\left| {\Gamma \left( x \right)} \right|} \right) &= \log \left( {\left| { \int\limits_0^\infty { {t^{\left( {x - 1} \right)} }\exp \left( { - t} \right)dt} } \right|} \right) 2860 | \end{aligned}$$ 2861 | 2862 | - Supported types are `Integer` or `Numeric` of a `Vector` or `Matrix`. 2863 | 2864 | - Examples: 2865 | 2866 | ```{Rcpp} 2867 | // Sample Data 2868 | NumericVector A = NumericVector::create(1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5); 2869 | 2870 | NumericVector B = gamma(A); 2871 | // Output: 1 0.886227 1 1.32934 2 3.32335 6 11.6317 24 2872 | 2873 | NumericVector C = lgamma(A); 2874 | // Output: 0 -0.120782 0 0.284683 0.693147 1.20097 1.79176 2.45374 3.17805 2875 | ``` 2876 | 2877 | #### Gamma Derivatives {#gamma-deriv} 2878 | 2879 | | | | 2880 | |:---------------------------|:--------------------| 2881 | | **psigamma( X , deriv )** | | 2882 | | **digamma( X )** | **trigamma( X )** | 2883 | | **tetragamma( X )** | **pentagamma( X )** | 2884 | 2885 | - Obtain the _n_^th^ derivative of the logarithm of the gamma function using 2886 | `psigamma`. For convenience, derivatives of the second, `digamma`, through 2887 | fifth, `pentagamma`, order have been defined. 2888 | 2889 | - **Definition:** 2890 | $$\begin{aligned} 2891 | {\psi _n}\left( x \right) &= \frac{ { {d^{n + 1} } } }{ {d{x^{n + 1} } } }\ln \Gamma \left( x \right) \\ 2892 | &= \frac{ { {d^n} } }{ {d{x^n} } }\frac{ {\Gamma '\left( x \right)} }{ {\Gamma \left( x \right)} } \\ 2893 | \end{aligned}$$ 2894 | 2895 | - The `deriv` parameter of the `psigamma` function specifies the derivative 2896 | to take of the logarithm of the gamma function. 2897 | 2898 | - For the `psigamma` function, only the `Numeric` type of the `Vector` and 2899 | `Matrix` class is supported. The convenience derivative functions have support 2900 | for both `Integer` and `Numeric` type of the `Vector` and `Matrix` class. 2901 | 2902 | - Examples: 2903 | 2904 | ```{Rcpp} 2905 | NumericVector A = NumericVector::create(1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5); 2906 | 2907 | NumericVector B = digamma(A); 2908 | // Output: -0.577216 0.03649 0.422784 0.703157 0.922784 1.10316 1.25612 1.38887 1.50612 2909 | 2910 | NumericVector C = trigamma(A); 2911 | // Output: 1.64493 0.934802 0.644934 0.490358 0.394934 0.330358 0.283823 0.248725 0.221323 2912 | 2913 | NumericVector D = tetragamma(A); 2914 | // Output: -2.40411 -0.828797 -0.404114 -0.236204 -0.154114 -0.108204 -0.0800397 -0.0615568 -0.0487897 2915 | 2916 | NumericVector E = pentagamma(A); 2917 | // Output: 6.49394 1.40909 0.493939 0.223906 0.118939 0.0703058 0.0448653 0.0303225 0.0214278 2918 | 2919 | // --- Trigamma derivative 2920 | NumericVector F = psigamma(A, 1.0); 2921 | // Output: 1.64493 0.934802 0.644934 0.490358 0.394934 0.330358 0.283823 0.248725 0.221323 2922 | ``` 2923 | 2924 | --- 2925 | 2926 | ### Factorials {#factorials} 2927 | 2928 | | | | 2929 | |:-------------------|:--------------------| 2930 | | **factorial( X )** | **lfactorial( X )** | 2931 | 2932 | - Compute the product of all positive integers less than or equal to _n_ using 2933 | `factorial` and the natural logarithm of the absolute value of the factorial 2934 | with `lfactorial`. 2935 | 2936 | - **Definition**: 2937 | $$\begin{aligned} 2938 | n! &= \prod\limits_{k = 1}^n { {k_i} } = 1 \times 2 \times \cdots \times \left( {n - 1} \right) \times n \\ 2939 | &= \begin{cases} 2940 | 1, &\text{if } n = 0 \\ 2941 | n\left( {n - 1} \right)!, &\text{if } n > 0 2942 | \end{cases} \\ 2943 | &= \Gamma\left(n+1\right) \\ 2944 | \log \left( {\left| {n!} \right|} \right) &= \log \left( {\left| {\Gamma \left( {n + 1} \right)} \right|} \right) 2945 | \end{aligned}$$ 2946 | 2947 | - Only the `Numeric` type of the `Vector` and `Matrix` class is supported. 2948 | 2949 | - Examples: 2950 | 2951 | ```{Rcpp} 2952 | // Sample Data 2953 | NumericVector A = NumericVector::create(1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5); 2954 | 2955 | NumericVector B = factorial(A); 2956 | // Output: 1 1.32934 2 3.32335 6 11.6317 24 52.3428 120 2957 | 2958 | NumericVector C = lfactorial(A); 2959 | // Output: 0 0.284683 0.693147 1.20097 1.79176 2.45374 3.17805 3.95781 4.78749 2960 | ``` 2961 | 2962 | ### Combinatorics {#combinatorics} 2963 | 2964 | | | | 2965 | |:-----------------------|:-----------------------| 2966 | | **choose( N , K )** | **lchoose( N , K)** | 2967 | 2968 | - Compute the binomial coefficients for all real numbers _n_ and integer _k_ using 2969 | `choose` and the natural logarithm of the absolute value of the binomial coefficients 2970 | with `lchoose`. 2971 | 2972 | - **Definition**: 2973 | $$\begin{aligned} 2974 | {n \choose k} &= \frac{n!}{k!\left( {n - k} \right)!} = \frac{n\left( {n - 1} \right) \cdots \left( {n - k + 1} \right)}{k!} \\ 2975 | \log \left( {\left| {n \choose k} \right|} \right) &= \log \left( {\left| {\frac{n\left( {n - 1} \right) \cdots \left( {n - k + 1} \right)}{k!} } \right|} \right) 2976 | \end{aligned}$$ 2977 | 2978 | - Only the `Numeric` type of the `Vector` and `Matrix` class is supported. 2979 | 2980 | - Examples: 2981 | 2982 | ```{Rcpp choose_sugar} 2983 | // Sample Data 2984 | NumericVector A = NumericVector::create(10, 9, 8, 7, 6); 2985 | NumericVector B = NumericVector::create(5, 4, 3, 2, 1); 2986 | 2987 | // --- Vectorize Choose 2988 | 2989 | NumericVector C = choose(A, B); 2990 | // Output: 252 126 56 21 6 2991 | 2992 | NumericVector D = lchoose(A, B); 2993 | // Output: 5.52943 4.83628 4.02535 3.04452 1.79176 2994 | 2995 | // --- Scalar Choose 2996 | 2997 | NumericVector E = choose(10.0, B); 2998 | // Output: 252 210 120 45 10 2999 | 3000 | NumericVector F = choose(A, 5.0); 3001 | // Output: 252 126 56 21 6 3002 | ``` 3003 | 3004 | --- 3005 | 3006 | ### Statistical Summaries {#sugar-stats} 3007 | 3008 | #### Minimum and Maximum {#min-max} 3009 | 3010 | | | | 3011 | |:-------------|:-------------| 3012 | | **min( X )** | **max( X )** | 3013 | 3014 | - Obtain the extremum value of either a maximum and minimum from within `Vector` 3015 | or `Matrix`. 3016 | 3017 | - Examples: 3018 | 3019 | ```{Rcpp min_v_max} 3020 | // Sample Data 3021 | NumericVector X = NumericVector::create(3, 4, 9, 5, 1, 2); 3022 | 3023 | // Obtain max value for X 3024 | double X_max = max(X); 3025 | // Output: 9 3026 | 3027 | // Obtain min value for X 3028 | double X_min = minx(X); 3029 | // Output: 1 3030 | ``` 3031 | 3032 | --- 3033 | 3034 | #### range( X ) {#range} 3035 | 3036 | - Computes the range or the minimum and maximum values of the sample. 3037 | 3038 | - Supported types are `Integer` or `Numeric` of a `Vector` or `Matrix`. 3039 | 3040 | ```{Rcpp range_vals} 3041 | // Sample Data 3042 | NumericVector X = NumericVector::create(3, 4, 9, 5, 1, 2); 3043 | 3044 | // Obtain range value for X 3045 | NumericVector X_range = range(X); 3046 | // Output: 1 9 3047 | ``` 3048 | 3049 | --- 3050 | 3051 | #### mean( X ) {#mean} 3052 | 3053 | - Computes the overall sample mean by summing each observation and dividing 3054 | by the total number of observations. 3055 | 3056 | - Definition: $$\bar{X} = \frac{1}{n}\sum\limits_{i = 1}^n { {X_i} } $$ 3057 | 3058 | - Supported types are `Integer`, `Numeric`, `Complex`, or `Logical` of a 3059 | `Vector` or `Matrix`. 3060 | 3061 | ```{Rcpp mean_val} 3062 | // Sample Data 3063 | NumericVector X = NumericVector::create(3, 4, 9, 5, 1, 2); 3064 | 3065 | // Obtain mean value for X 3066 | double X_mean = mean(X); 3067 | // Output: 4 3068 | ``` 3069 | 3070 | - See also: 3071 | - [`colMeans` / `rowMeans`](#matrix-mean) 3072 | 3073 | --- 3074 | 3075 | #### median( X , na_rm) {#median} 3076 | 3077 | - Computes the sample median by ordering elements from largest to smallest and 3078 | then selecting the middle element. If an even number of elements is present, 3079 | then the median consists of an average between the two middle numbers. 3080 | 3081 | - All types of a `Vector` or `Matrix` are supported. 3082 | 3083 | - Examples: 3084 | 3085 | ```{Rcpp median_val} 3086 | // Sample Data 3087 | NumericVector X = NumericVector::create(3,4,9,5,NA_REAL,1,2); 3088 | 3089 | // Obtain the median value for X by removing NAs 3090 | double X_median = median(X, true); 3091 | // Output: 3.5 3092 | 3093 | // By default, NA is not removed 3094 | double X_median_na = median(X); 3095 | // Output: NaN 3096 | ``` 3097 | 3098 | 3099 | --- 3100 | 3101 | #### Variance {#var} 3102 | 3103 | | | | 3104 | |:-------------|:------------| 3105 | | **var( X )** | **sd( X )** | 3106 | 3107 | 3108 | - Computes the _sample_ variance and standard deviation formula by taking the 3109 | corrected sum of squares and dividing it by $N-1$. 3110 | 3111 | - Definition: $$\begin{aligned} 3112 | \operatorname{var}\left( X \right) &= \frac{1}{n-1}\sum\limits_{i = 1}^n { { {\left( { {X_i} - \bar X} \right)}^2} } \\ 3113 | \operatorname{sd}\left( X \right) &= \sqrt{\operatorname{var}\left( X \right)} 3114 | \end{aligned}$$ 3115 | 3116 | - **Note:** No parameter support exists to switch between _population_ ($\frac{1}{n}$) 3117 | and _sample_ ($\frac{1}{n-1}$) definitions. If necessary, multiple by the 3118 | multiplication by `double(n-1)/n` should provide the appropriate conversion. 3119 | 3120 | - Supported types are `Integer`, `Numeric`, `Complex`, or `Logical` of a 3121 | `Vector` or `Matrix`. 3122 | 3123 | ```{Rcpp} 3124 | // Sample data 3125 | NumericVector X = NumericVector::create(5.3, 1.9, 7.4, 4.5, 2.5); 3126 | 3127 | // --- Compute the Variance 3128 | double var_val = var(X); 3129 | // Output: 4.912 3130 | 3131 | // --- Compute the SD 3132 | double sd_val = SD(X); 3133 | // Output: 2.216303 3134 | ``` 3135 | 3136 | --- 3137 | 3138 | ### Special Operations {#sugar-special-ops} 3139 | 3140 | #### rev( X ) {#rev} 3141 | 3142 | - Reverse the position of the elements within the vector. 3143 | 3144 | - All types are supported of a `Vector` or `Matrix`. 3145 | 3146 | - Example: 3147 | 3148 | ```{Rcpp rev_vec} 3149 | // Sample data 3150 | NumericVector A = NumericVector::create(1, 10, 100, 1000, 10000); 3151 | 3152 | // --- Reverse the vector 3153 | NumericVector B = rev(A); 3154 | // Output: 10000 1000 100 10 1 3155 | ``` 3156 | 3157 | ---- 3158 | 3159 | 3160 | #### Parallel Extremum {#pext} 3161 | 3162 | | | | 3163 | |:------------------|:-------------------| 3164 | | **pmax( X, Y )** | **pmin( X, Y )** | 3165 | 3166 | - Obtain a parallel extremum value of either maximum and minimum for either 3167 | a scalar and a `Vector` or just two `Vector` objects. 3168 | 3169 | - For instance, the parallel minimum of X = 0, 1 and Y = 2, -3 would be Z = 0, -3. 3170 | 3171 | - Examples: 3172 | 3173 | ```{Rcpp parallel_ext} 3174 | // Sample Data 3175 | NumericVector A = NumericVector::create(1,3,2,4,6,5); 3176 | NumericVector B = NumericVector::create(2,1,3,5,4,6); 3177 | 3178 | // --- Parallel Maximum 3179 | 3180 | // Scalar and Vector 3181 | NumericVector C = pmax(2, A); 3182 | // Output: 2 3 2 4 6 5 3183 | 3184 | // Two vectors 3185 | NumericVector D = pmax(A, B); 3186 | // Output: 2 3 3 5 6 6 3187 | 3188 | // --- Parallel Minimum 3189 | 3190 | // Scalar and Vector 3191 | NumericVector E = pmin(2, A); 3192 | // Output: 1 2 2 2 2 2 3193 | 3194 | // Two vectors 3195 | NumericVector F = pmin(A, B); 3196 | // Output: 1 1 2 4 4 5 3197 | ``` 3198 | 3199 | #### clamp( min , X , max ) {#clamp} 3200 | 3201 | - Bound elements of `X` between `min` and `max` by replacing the element by 3202 | the boundary if $X < min$ or $X > max$. 3203 | 3204 | - An alternate version of this function can be obtained with 3205 | `pmax(min, pmin(X, max) )`. 3206 | 3207 | - Example: 3208 | 3209 | ```{Rcpp clamp_val} 3210 | // Sample Data 3211 | NumericVector A = NumericVector::create(-3.4, 5.1, -8.1, 10.8, 2.9, 4.3, 15.5); 3212 | 3213 | // --- Clamp values 3214 | 3215 | // Remove negative values and any value above 10 3216 | NumericVector C = clamp(0.0, A, 10.0); 3217 | // Output: 0.0 5.1 0.0 10.0 2.9 4.3 10.0 3218 | ``` 3219 | 3220 | - See also: 3221 | - [Rcpp Gallery: Using the Rcpp sugar function `clamp`](http://gallery.rcpp.org/articles/sugar-function-clamp/) 3222 | - [`pmax`, `pmin`](#pext) 3223 | 3224 | ---- 3225 | 3226 | #### Extremum Indice {#which} 3227 | 3228 | | | | 3229 | |:--------------------|:-------------------| 3230 | | **which_min( X )** | **which_max( X )** | 3231 | 3232 | - Provides the position in the vector of the minimum or maximum value. 3233 | 3234 | - All types are supported of a `Vector` or a `Matrix`. 3235 | 3236 | - Examples: 3237 | 3238 | ```{Rcpp ids_min_v_max} 3239 | // Sample data 3240 | NumericVector A = NumericVector::create(3.2, 5.2, -9.7, 4.3, 8.8); 3241 | 3242 | // Return index for min value 3243 | int min_idx = which_min(A); 3244 | // Output: 2 (because C++ indices starts at 0!) 3245 | 3246 | // Return index for max value 3247 | int max_idx = which_max(A); 3248 | // Output: 4 (because C++ indices starts at 0!) 3249 | ``` 3250 | 3251 | - See also: 3252 | - [`min`, `max`](#min-max) 3253 | 3254 | ---- 3255 | 3256 | ### Uniqueness Operators {#sugarunique} 3257 | 3258 | #### match( X , Y ) {#match} 3259 | 3260 | - Obtain the first locations of a match between elements in _X_ and _Y_. 3261 | 3262 | - All types are supported of a `Vector` or a `Matrix`. 3263 | 3264 | - Example: 3265 | 3266 | ```{Rcpp match} 3267 | CharacterVector A = CharacterVector::create("a", "b"); 3268 | CharacterVector B = CharacterVector::create("c", "a", "b", "c", "e", "a", "b", "d"); 3269 | 3270 | IntegerVector C = match(A, B); 3271 | // Output: 2 3 3272 | ``` 3273 | 3274 | - See also: 3275 | - [`in`](#in) 3276 | - [`self_match`](#self-match) 3277 | 3278 | ---- 3279 | 3280 | #### self_match( X ) {#self-match} 3281 | 3282 | - Obtain the locations of where each element occurs in the object. 3283 | 3284 | - All types are supported of a `Vector` or a `Matrix`. 3285 | 3286 | - **Note:** This operation is similar to the _R_ command `match(x, unique(x))`. 3287 | 3288 | - Example: 3289 | 3290 | ```{Rcpp self_match} 3291 | CharacterVector A = CharacterVector::create("a", "b", "c", "c", "e", "b", "d"); 3292 | 3293 | IntegerVector B = self_match(A); 3294 | // Output: 1 2 3 3 4 2 5 3295 | ``` 3296 | 3297 | - See also: 3298 | - [`match`](#match) 3299 | 3300 | ---- 3301 | 3302 | #### in( X , Y ) {#in} 3303 | 3304 | - Determine whether elements in _X_ are found in _Y_. 3305 | 3306 | - All types are supported of a `Vector` or a `Matrix`. 3307 | 3308 | - Example: 3309 | 3310 | ```{Rcpp in_operator} 3311 | CharacterVector A = CharacterVector::create("a", "b", "c", "c", "e", "b", "d"); 3312 | 3313 | CharacterVector B = CharacterVector::create("a", "b"); 3314 | 3315 | LogicalVector C = in(A, B); 3316 | // Output: TRUE TRUE FALSE FALSE FALSE TRUE FALSE 3317 | ``` 3318 | 3319 | - See also: 3320 | - [`match`](#match) 3321 | - [`self_match`](#self-match) 3322 | 3323 | ---- 3324 | 3325 | #### Unique {#unique} 3326 | 3327 | | | | 3328 | |:--------------------|:----------------| 3329 | | **duplicated( X )** | **unique( X )** | 3330 | 3331 | - Determine whether duplicates exist within a `Vector` or what the unique values 3332 | are. 3333 | 3334 | - Duplicated values are identified by a `LogicalVector` such that the first, 3335 | second, and so on replicates are labeled as `TRUE` while unique values are `FALSE`. 3336 | 3337 | - Unique provides only the first occurrence of a given value. In essence, only 3338 | the values that appear as `FALSE` within the `duplicate` function. 3339 | 3340 | - Examples: 3341 | 3342 | ```{Rcpp unique_v_duplicates} 3343 | // Sample data 3344 | CharacterVector A = CharacterVector::create("a","b","c","a","b","c","a"); 3345 | 3346 | // Detect duplicates within a string 3347 | LogicalVector B = duplicated(A); 3348 | // Output: FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE 3349 | 3350 | // Obtain only unique values 3351 | CharacterVector C = unique(A); 3352 | // Output: "a", "b", "c" 3353 | ``` 3354 | 3355 | ---- 3356 | 3357 | ### sort_unique( X ) {#sort_unique} 3358 | 3359 | - Determine the unique elements within an object and sort them in increasing order. 3360 | 3361 | - All types are supported of a `Vector` or a `Matrix`. 3362 | 3363 | - Examples: 3364 | 3365 | ```{Rcpp sort_unique} 3366 | // Sample data 3367 | CharacterVector A = CharacterVector::create("a","b","c","a","b","c","a"); 3368 | NumericVector B = NumericVector::create(1.1, 1, 1, 2.5, 2.5, 3, 3); 3369 | 3370 | // --- Find unique values and sort them 3371 | 3372 | CharacterVector C = sort_unique(A); 3373 | // Output: "a" "b" "c" 3374 | 3375 | NumericVector D = sort_unique(B); 3376 | // Output: 1 1.1 2.5 3 3377 | ``` 3378 | 3379 | ---- 3380 | 3381 | ### table( X ) {#table} 3382 | 3383 | - Given a `Vector` of either `NumericVector`, `IntegerVector`, `LogicalVector`, 3384 | or `CharacterVector`, compute an `IntegerVector` that contains a count of 3385 | each value. 3386 | 3387 | - Examples: 3388 | 3389 | ```{Rcpp rcpp_table} 3390 | // Needs to have a way to extract what value is represented at each position 3391 | // names attribute? 3392 | 3393 | // Create Numerical Data 3394 | NumericVector A = NumericVector::create(3.2, 1.2, -0.5, NA_REAL, 1.2, 2.0, NA_REAL); 3395 | 3396 | // Tabulate 3397 | IntegerVector B = table(A); 3398 | 3399 | // Create Integer Data 3400 | IntegerVector C = IntegerVector::create(2, -2, NA_INTEGER, NA_INTEGER, 200, 2); 3401 | 3402 | // Tabulate the integer data 3403 | IntegerVector D = table(C); 3404 | 3405 | // Create Character Data 3406 | CharacterVector E = CharacterVector::create("a", "a", "b", NA_STRING, "c", NA_STRING); 3407 | 3408 | // Tabulate 3409 | IntegerVector F = table(E); 3410 | 3411 | // Create Logical Data 3412 | LogicalVector G = LogicalVector::create(true, NA_LOGICAL, false, true, NA_LOGICAL); 3413 | 3414 | // Tabulate 3415 | IntegerVector H = table(G); 3416 | ``` 3417 | 3418 | ---- 3419 | 3420 | ### Set Operations {#sugar-set-ops} 3421 | 3422 | #### setequal(X, Y) {#setequal} 3423 | 3424 | - Determine if the values of two objects are equal. 3425 | 3426 | - **Definition:** $$A = B = \left\{ {\forall x:x \in A \wedge x \in B} \right\}$$ 3427 | 3428 | - All types are supported of a `Vector` or `Matrix`. 3429 | 3430 | - Examples: 3431 | 3432 | ```{Rcpp set_equal} 3433 | // Sample Data for equal case 3434 | CharacterVector A = CharacterVector::create("a", "b", "c"); 3435 | CharacterVector B = CharacterVector::create("c", "b", "a"); 3436 | 3437 | // Sample Data for unequal case 3438 | CharacterVector C = CharacterVector::create("a", "b"); 3439 | CharacterVector D = CharacterVector::create("c"); 3440 | 3441 | bool val_equal_set = setequal(A, B); 3442 | // Output: TRUE 3443 | 3444 | bool val_unequal_set = setequal(C, D); 3445 | // Output: FALSE 3446 | ``` 3447 | 3448 | ---- 3449 | 3450 | #### intersect(X, Y) {#intersect} 3451 | 3452 | - Find all elements two objects have in common. 3453 | 3454 | - **Definition:** $$A \cap B = \left\{ {x:x \in A \wedge x \in B} \right\}$$ 3455 | 3456 | - All types are supported of a `Vector` or `Matrix`. 3457 | 3458 | - Examples: 3459 | 3460 | ```{Rcpp set_intersect} 3461 | // Sample Data for equal case 3462 | CharacterVector A = CharacterVector::create("a", "b", "c"); 3463 | CharacterVector B = CharacterVector::create("c", "b", "d"); 3464 | 3465 | // Sample Data for empty set 3466 | CharacterVector C = CharacterVector::create("a", "b"); 3467 | CharacterVector D = CharacterVector::create("c"); 3468 | 3469 | CharacterVector E = intersect(A, B); 3470 | // Output: "b" "c" 3471 | 3472 | CharacterVector F = intersect(C, D); 3473 | // Output: 3474 | // (Empty set/None) 3475 | ``` 3476 | 3477 | ---- 3478 | 3479 | #### union_(X, Y) {#union} 3480 | 3481 | - Obtaining only one copy of all elements that exist in both sets. 3482 | 3483 | - **Definition:** $$A \cup B = \left\{ {x:x \in A \vee x \in B} \right\}$$ 3484 | 3485 | - All types are supported of a `Vector` or `Matrix`. 3486 | 3487 | - **Note:** Union has a postfix of an underscore (`_`) because 3488 | `union` is a keyword in C++. 3489 | 3490 | - Examples: 3491 | 3492 | ```{Rcpp set_union} 3493 | // Sample Data for overlapping elements 3494 | CharacterVector A = CharacterVector::create("a", "b", "c"); 3495 | CharacterVector B = CharacterVector::create("c", "b", "d"); 3496 | 3497 | // Sample Data for no shared elements 3498 | CharacterVector C = CharacterVector::create("a", "b"); 3499 | CharacterVector D = CharacterVector::create("c"); 3500 | 3501 | // --- Calling union_ 3502 | 3503 | CharacterVector E = union_(A, B); 3504 | // Output: "d" "a" "c" "b" 3505 | 3506 | CharacterVector F = union_(C, D); 3507 | // Output: "a" "c" "b" 3508 | ``` 3509 | 3510 | ---- 3511 | 3512 | #### setdiff(X, Y) {#setdiff} 3513 | 3514 | - Obtain the elements in _A_ not in _B_ or the intersection of _A_ with the 3515 | complement of _B_. 3516 | 3517 | - **Definition:** $$A\backslash B = A - B = A \cap {B^C} = \left\{ {x:x \in A \wedge x \notin B} \right\}$$ 3518 | 3519 | - All types are supported of a `Vector` or `Matrix`. 3520 | 3521 | - Examples: 3522 | 3523 | ```{Rcpp set_diff} 3524 | // Sample Data for overlapping elements 3525 | CharacterVector A = CharacterVector::create("a", "b", "c"); 3526 | CharacterVector B = CharacterVector::create("c", "b", "d"); 3527 | 3528 | // Sample Data for no shared elements 3529 | CharacterVector C = CharacterVector::create("a", "b"); 3530 | CharacterVector D = CharacterVector::create("c"); 3531 | 3532 | // --- Calling setdiff 3533 | 3534 | CharacterVector E = setdiff(A, B); 3535 | // Output: "a" 3536 | 3537 | // Note order results in different values! 3538 | CharacterVector F = setdiff(B, A); 3539 | // Output: "d" 3540 | 3541 | CharacterVector G = setdiff(C, D); 3542 | // Output: "a" "b" 3543 | ``` 3544 | 3545 | ---- 3546 | 3547 | 3548 | ### Matrix Operations {#sugar-matrix-ops} 3549 | 3550 | #### Row and Column Sums {#matrix-sum} 3551 | 3552 | | | | 3553 | |:-------------------------|:-------------------------| 3554 | | **colSums( X , na_rm)** | **rowSums( X , na_rm )** | 3555 | 3556 | - Computes the summation of elements either by column (`colSums`) or row (`rowSums`) 3557 | of a `Matrix`. 3558 | 3559 | - **Definition:** 3560 | 3561 | $$\begin{aligned} 3562 | \text{(Row) } { {X}_{i} } &= \sum\limits_{j = 1}^J { {X_{i,j} }} \\ 3563 | \text{(Column) } { {X}_{j} } &= \sum\limits_{i = 1}^I { {X_{i,j} }} \\ 3564 | \end{aligned} $$ 3565 | 3566 | - Supported types are `Numeric`, `Integer` or `Complex` of the `Matrix` class. 3567 | 3568 | - The return type is the equivalent input type but of the `Vector` class. 3569 | 3570 | - Examples: 3571 | 3572 | ```{Rcpp} 3573 | NumericVector A = NumericVector::create(1.0, 2.0, 3.0, 4.0); 3574 | NumericMatrix B = NumericMatrix(2, 2, A.begin()); 3575 | // Output: 3576 | // 1.00000 3.00000 3577 | // 2.00000 4.00000 3578 | 3579 | // --- Various matrix sums 3580 | 3581 | NumericVector C = colSums(B); 3582 | // Output: 3 7 3583 | 3584 | NumericVector D = rowSums(B); 3585 | // Output: 4 6 3586 | ``` 3587 | 3588 | - See also: 3589 | - [`sum`](#sum) 3590 | 3591 | ---- 3592 | 3593 | #### Row and Column Means {#matrix-mean} 3594 | 3595 | | | | 3596 | |:--------------------------|:-------------------------| 3597 | | **colMeans( X , na_rm)** | **rowMeans( X , na_rm)** | 3598 | 3599 | 3600 | - Computes the means of elements either by column (`colMeans`) or row (`rowMeans`) 3601 | of a `Matrix`. 3602 | 3603 | - **Definition:** 3604 | 3605 | $$\begin{aligned} 3606 | \text{(Row) } { {\bar X}_{i} } &= \frac{1}{J}\sum\limits_{j = 1}^J { {X_{i,j} }} \\ 3607 | \text{(Column) }{ {\bar X}_{j} } &= \frac{1}{I}\sum\limits_{i = 1}^I { {X_{i,j} }} \\ 3608 | \end{aligned} $$ 3609 | 3610 | - Supported types are `Numeric`, `Integer` or `Complex` of the `Matrix` class. 3611 | 3612 | - The return type is the equivalent input type but of the `Vector` class. 3613 | 3614 | - Examples: 3615 | 3616 | ```{Rcpp} 3617 | NumericVector A = NumericVector::create(1.0, 2.0, 3.0, 4.0); 3618 | NumericMatrix B = NumericMatrix(2, 2, A.begin()); 3619 | // Output: 3620 | // 1.00000 3.00000 3621 | // 2.00000 4.00000 3622 | 3623 | // --- Various matrix means 3624 | 3625 | NumericVector C = colMeans(B); 3626 | // Output: 1.5 3.5 3627 | 3628 | NumericVector D = rowMeans(B); 3629 | // Output: 2 3 3630 | ``` 3631 | 3632 | - See also: 3633 | - [`mean`](#mean) 3634 | 3635 | ---- 3636 | 3637 | #### outer( X , Y , Function) {#outer} 3638 | 3639 | 3640 | - Applies a `Function` to two `Vector` objects to obtain the outer product. 3641 | 3642 | - **Definition:** $$\begin{aligned} 3643 | f\left( {\vec u \otimes \vec v} \right) &= f\left( {\vec u{ {\vec v}^T} } \right) = f\left( {\left[ {\begin{array}{*{20}{c} } 3644 | { {u_1} } \\ 3645 | \vdots \\ 3646 | { {u_n} } 3647 | \end{array} } \right]\left[ {\begin{array}{*{20}{c} } 3648 | { {v_1} }& \cdots &{ {v_n} } 3649 | \end{array} } \right]} \right) \hfill \\ 3650 | &= \left[ {\begin{array}{*{20}{c} } 3651 | {f\left( { {u_1}{v_1} } \right)}&{f\left( { {u_1}{v_2} } \right)}& \cdots &{f\left( { {u_1}{v_n} } \right)} \\ 3652 | {f\left( { {u_2}{v_1} } \right)}&{f\left( { {u_2}{v_2} } \right)}&{}&{f\left( { {u_2}{v_n} } \right)} \\ 3653 | \vdots &{}& \ddots & \vdots \\ 3654 | {f\left( { {u_n}{v_1} } \right)}&{f\left( { {u_n}{v_2} } \right)}&{}&{f\left( { {u_n}{v_n} } \right)} 3655 | \end{array} } \right] \hfill \\ 3656 | \end{aligned}$$ 3657 | 3658 | - All types of the `Vector` class are supported. However, the supplied `Function` 3659 | must have the correct parameter input types to receive values from each `Vector`. 3660 | 3661 | - The returned value is a `Matrix` class with its type given by the valued returned by the `Function`. 3662 | 3663 | - The `Function` parameter also accepts a C++ `functor` in place of an Rcpp `Function`. 3664 | In such cases, the underlying type _T_ must be defined. Select one of the following arguments for _T_: 3665 | - `int` 3666 | - `double` 3667 | - `std::complex / Rcomplex` 3668 | - `bool` 3669 | 3670 | - `Numeric` Output 3671 | 3672 | | Functor | Meaning | 3673 | |:---------------------------|:---------------------| 3674 | | `std::plus()` | `x + y` | 3675 | | `std::minus()` | `x - y` | 3676 | | `std::multiplies()` | `x * y` | 3677 | | `std::divides()` | `x / y` | 3678 | | `std::modulus()` | `x % y` | 3679 | 3680 | - `Logical` Output 3681 | 3682 | | Functor | Meaning | 3683 | |:---------------------------|:---------------------| 3684 | | `std::equal_to()` | `x == y` | 3685 | | `std::not_equal_to()` | `x != y` | 3686 | | `std::greater()` | `x > y` | 3687 | | `std::less()` | `x < y` | 3688 | | `std::greater_equal()` | `x >= y` | 3689 | | `std::less_equal()` | `x <= y` | 3690 | 3691 | 3692 | - Examples: 3693 | 3694 | ```{Rcpp} 3695 | // Sample Data 3696 | NumericVector A = NumericVector::create(0.5, 1.0, 1.5, 2.0); 3697 | NumericVector B = NumericVector::create(0.0, 0.5, 1.0, 1.5); 3698 | 3699 | // --- Applying outer with functors 3700 | 3701 | NumericMatrix C = outer(A, B, std::plus()); 3702 | // Output: 3703 | // 0.5 1.0 1.5 2.0 3704 | // 1.0 1.5 2.0 2.5 3705 | // 1.5 2.0 2.5 3.0 3706 | // 2.0 2.5 3.0 3.5 3707 | 3708 | LogicalMatrix D = outer(A, B, std::less()); 3709 | // Output: 3710 | // FALSE FALSE TRUE TRUE 3711 | // FALSE FALSE FALSE TRUE 3712 | // FALSE FALSE FALSE FALSE 3713 | // FALSE FALSE FALSE FALSE 3714 | ``` 3715 | 3716 | - See also: 3717 | - [cppreference: Operator function objects](http://en.cppreference.com/w/cpp/utility/functional#Operator_function_objects) 3718 | 3719 | ---- 3720 | 3721 | #### Triangle Matrix Views {#tri-mat} 3722 | 3723 | | | | 3724 | |:--------------------------|:--------------------------| 3725 | | **lower_tri( X , diag)** | **upper_tri( X , diag )** | 3726 | 3727 | - Creates a `Matrix` of `Logical` values of the same dimensions as the supplied 3728 | `Matrix` with values in the lower or upper triangle portion being `true`. 3729 | 3730 | - All types are supported of the `Matrix` class. 3731 | 3732 | - By default, the `diag` parameter is `false` and, therefore, does _not_ 3733 | include the major diagonal (upper left to lower right). 3734 | 3735 | - **Note:** Prior to Rcpp 0.13.0, neither the `upper_tri` or the `lower_tri` 3736 | function worked. 3737 | 3738 | - Examples: 3739 | 3740 | ```{Rcpp} 3741 | NumericVector A = NumericVector::create(1, 2, 3, 4, 5, 6, 7, 8, 9); 3742 | NumericMatrix B = NumericMatrix(3, 3, A.begin()); 3743 | // Output: 3744 | // 1.00000 4.00000 7.00000 3745 | // 2.00000 5.00000 8.00000 3746 | // 3.00000 6.00000 9.00000 3747 | 3748 | // --- Lower Triangular Matrix 3749 | 3750 | LogicalMatrix E = lower_tri(B); 3751 | // Output: 3752 | // FALSE FALSE FALSE 3753 | // TRUE FALSE FALSE 3754 | // TRUE TRUE TRUE 3755 | 3756 | LogicalMatrix F = lower_tri(B, true); 3757 | // Output: 3758 | // TRUE FALSE FALSE 3759 | // TRUE TRUE FALSE 3760 | // TRUE TRUE TRUE 3761 | 3762 | // --- Upper Triangular Matrix 3763 | 3764 | LogicalMatrix C = upper_tri(B); 3765 | // Output: 3766 | // FALSE TRUE TRUE 3767 | // FALSE FALSE TRUE 3768 | // FALSE FALSE FALSE 3769 | 3770 | LogicalMatrix D = upper_tri(B, true); 3771 | // Output: 3772 | // TRUE TRUE TRUE 3773 | // FALSE TRUE TRUE 3774 | // FALSE FALSE TRUE 3775 | ``` 3776 | 3777 | ---- 3778 | 3779 | #### diag( X ) {#diag} 3780 | 3781 | - Extracts the major diagonal going from the upper left to lower right of a 3782 | `Matrix`. 3783 | 3784 | - All types of the `Matrix` class are supported. 3785 | 3786 | - The return type is a `Vector` of an equivalent type to the input `Matrix`. 3787 | 3788 | - Example: 3789 | 3790 | ```{Rcpp} 3791 | NumericVector A = NumericVector::create(1, 2, 3, 4, 5, 6, 7, 8, 9); 3792 | NumericMatrix B = NumericMatrix(3, 3, A.begin()); 3793 | // Output: 3794 | // 1.00000 4.00000 7.00000 3795 | // 2.00000 5.00000 8.00000 3796 | // 3.00000 6.00000 9.00000 3797 | 3798 | NumericVector C = diag(B); 3799 | // Output: 1 5 9 3800 | ``` 3801 | 3802 | 3803 | ---- 3804 | 3805 | #### Matrix Indexes {#idx-mat} 3806 | 3807 | | | | 3808 | |:--------------|:-------------| 3809 | | **col( X )** | **row( X )** | 3810 | 3811 | 3812 | - Creates a `Matrix` where each element contains either a 1-based index for its 3813 | column (`col`) or row (`row`). 3814 | 3815 | - All types of the `Matrix` class are supported. 3816 | 3817 | - The return type is an `IntegerMatrix`. 3818 | 3819 | - Examples: 3820 | 3821 | ```{Rcpp} 3822 | NumericVector A = NumericVector::create(1.0, 2.0, 3.0, 4.0); 3823 | NumericMatrix B = NumericMatrix(2, 2, A.begin()); 3824 | // Output: 3825 | // 1.00000 3.00000 3826 | // 2.00000 4.00000 3827 | 3828 | // --- Various Matrix Indexes 3829 | 3830 | IntegerMatrix C = col(B); 3831 | // Output: 3832 | // 1 2 3833 | // 1 2 3834 | 3835 | 3836 | IntegerMatrix D = row(B); 3837 | // Output: 3838 | // 1 1 3839 | // 2 2 3840 | ``` 3841 | 3842 | ---- 3843 | 3844 | ### Object Creation {#sugar-object-creation} 3845 | 3846 | #### cbind {#cbind} 3847 | 3848 | | | 3849 | |:---------------------| 3850 | | **cbind(X, Y)** | 3851 | | **cbind(X, Y, ...)** | 3852 | 3853 | 3854 | **cbind(X, Y, ...)** 3855 | 3856 | - Creates a `Matrix` by joining objects together in a column-wise manner. 3857 | 3858 | - *X*, *Y* may be any combination of `Vector`, `Matrix`, or atomic value 3859 | of the same underlying type *T*, where *T* is one of 3860 | - `int` 3861 | - `double` 3862 | - `std::complex / Rcomplex` 3863 | - `bool` 3864 | 3865 | - `cbind` is defined for any number of arguments between 2 and 50, inclusive. 3866 | 3867 | - Let *S1* and *S2* be scalar (atomic) values, *V* be a `Vector` with length k, 3868 | and *M* be a `Matrix` with with m rows and n columns. The `cbind` function 3869 | exhibits the following behavior: 3870 | - `cbind(S1, S2)` returns a 1 x 2 `Matrix`. 3871 | - `cbind(S1, V)` and `cbind(V, S1)` return a k x 2 `Matrix`, where *S1* is 3872 | recycled k times. 3873 | - `cbind(S1, M)` and `cbind(M, S1)` return an m x (n + 1) `Matrix`, where 3874 | `S1` is recycled m times. 3875 | - If k and m are equal, `cbind(V, M)` and `cbind(M, V)` return an m x n 3876 | `Matrix`. 3877 | - If k and m are not equal, `cbind(V, M)` and `cbind(M, V)` will throw an 3878 | exception at runtime. 3879 | - *S1* and *S2* may be consecutive arguments in a `cbind` expression IFF: 3880 | - they are the *only* arguments used; or 3881 | - all other arguemnts are also scalars; or 3882 | - non-scalar, adjacent arguments are vectors of length one, or matrices 3883 | with one row. 3884 | - All other cases involving consecutive arguments *S1* and *S2* will 3885 | generate a runtime error. 3886 | 3887 | - Examples: 3888 | 3889 | ```{Rcpp, cbind} 3890 | double d = 1.0; 3891 | NumericVector v(3, 2.0); 3892 | NumericMatrix m(3, 2); 3893 | m.fill(3.0); 3894 | 3895 | Rcout 3896 | << std::setprecision(2) 3897 | << "cbind(1.5, 2.5):\n" << cbind(1.5, 2.5) << "\n" 3898 | << "cbind(d, v):\n" << cbind(d, v) << "\n" 3899 | << "cbind(v, d):\n" << cbind(v, d) << "\n" 3900 | << "cbind(d, v, m, v, d):\n" << cbind(d, v, m, v, d) 3901 | << std::endl; 3902 | // Output: 3903 | // cbind(1.5, 2.5): 3904 | // 1.5 2.5 3905 | // 3906 | // cbind(d, v): 3907 | // 1.0 2.0 3908 | // 1.0 2.0 3909 | // 1.0 2.0 3910 | // 3911 | // cbind(v, d): 3912 | // 2.0 1.0 3913 | // 2.0 1.0 3914 | // 2.0 1.0 3915 | // 3916 | // cbind(d, v, m, v, d): 3917 | // 1.0 2.0 3.0 3.0 2.0 1.0 3918 | // 1.0 2.0 3.0 3.0 2.0 1.0 3919 | // 1.0 2.0 3.0 3.0 2.0 1.0 3920 | ``` 3921 | 3922 | #### Sequence Generation {#seq} 3923 | 3924 | | | | 3925 | |:--------------------|:---------------------| 3926 | | **seq_along( X )** | **seq_len( n )** | 3927 | 3928 | - Generate an `Integer` sequence with the index beginning at 1 either based on 3929 | an object (`seq_along`) or length (`seq_len`). 3930 | 3931 | - All types are supported of a `Vector` or `Matrix`. 3932 | 3933 | - The return type is that of an `IntegerVector`. 3934 | 3935 | - Examples: 3936 | 3937 | ```{Rcpp} 3938 | NumericVector A = NumericVector::create(-1, 0, 1); 3939 | 3940 | // By default, seq_along returns R indices 3941 | IntegerVector B = seq_along(A); 3942 | // Output: 1 2 3 3943 | 3944 | // Generates a vector of specified length 3945 | IntegerVector C = seq_len(5); 3946 | // Output: 1 2 3 4 5 3947 | ``` 3948 | 3949 | 3950 | ---- 3951 | 3952 | #### Replicate Elements {#rep} 3953 | 3954 | | | | | 3955 | |:--------------------|:---------------------|:---------------------| 3956 | | **rep( X, n )** | **rep_each( X, n )** | **rep_len( X, n )** | 3957 | 3958 | - Replicate elements in three flavors: 3959 | - `rep`: duplicate the object _n_ times retaining the initial element order. 3960 | - `rep_each`: each element is repeated _n_ times consecutively. 3961 | - `rep_len`: duplicate object until the new object has length of _n_. 3962 | 3963 | - All types are supported of a `Vector` or `Matrix`. 3964 | 3965 | - Examples: 3966 | 3967 | ```{Rcpp} 3968 | NumericVector A = NumericVector::create(-1, 0, 1); 3969 | 3970 | NumericVector B = rep(A, 3); 3971 | // Output: -1 0 1 -1 0 1 -1 0 1 3972 | 3973 | NumericVector C = rep_each(A, 3); 3974 | // Output: -1 -1 -1 0 0 0 1 1 1 3975 | 3976 | NumericVector D = rep_len(A, 5); 3977 | // Output: -1 0 1 -1 0 3978 | ``` 3979 | 3980 | ### String Operations {#sugar-string-ops} 3981 | 3982 | #### collapse( X ) {#collapse} 3983 | 3984 | - Collapse multiple strings values into a single string. 3985 | 3986 | - Only the `Character` and `String` types of a `Vector` or `Matrix` are 3987 | supported. 3988 | 3989 | - **Note:** The function is equivalent to `paste(c('a', 'b'), collapse = "")`. 3990 | 3991 | - Example: 3992 | 3993 | ```{Rcpp sugar_collapse} 3994 | CharacterVector A = CharacterVector::create("w","o","r","l","d"); 3995 | 3996 | std::string val_str = collapse(A); 3997 | // Output: world 3998 | ``` 3999 | 4000 | #### trimws( X, which ) {#trimws} 4001 | 4002 | - Trim leading and/or trailing whitespace from strings. 4003 | 4004 | - The `which` argument controls how the trimming is performed. 4005 | This is **required** and can be specified with either 4006 | `"l"` (leading), `"r"` (trailing), or `"b"` (both). 4007 | 4008 | - Only the `Character` and `String` types of a `Vector` or `Matrix` are 4009 | supported. 4010 | 4011 | - This function provides support for returning either a `String`, `Vector`, or 4012 | `Matrix` depending on the supplied parameter. 4013 | 4014 | - Definition: **Whitespace** in the context of this function is considered to 4015 | be either: space (` `), horizontal tab (`\t`), line feed (`\n`), or 4016 | carriage return (`\r`). 4017 | 4018 | - **Note:** The function is equivalent to matching the following 4019 | regular expression (regex) patterns: 4020 | - `^[ \t\r\n]+` (left/leading) 4021 | - `[ \t\r\n]+$` (right/trailing) 4022 | - `^[ \t\r\n]+|[ \t\r\n]+$` (both) 4023 | 4024 | - Example: 4025 | 4026 | ```{Rcpp sugar_trimws} 4027 | // -- Example Data 4028 | CharacterVector A = CharacterVector::create(" a b c", "a b c ", " a b c "); 4029 | 4030 | Rcpp::String B = " \t\r\na b c\t\r\n "; 4031 | 4032 | CharacterMatrix C = cbind(A, B); 4033 | 4034 | // -- Vectors 4035 | 4036 | CharacterVector D = trimws(A, "r"); 4037 | // Output: " a b c" "a b c" " a b c" 4038 | 4039 | CharacterVector E = trimws(A, "l"); 4040 | // Output: "a b c" "a b c " "a b c " 4041 | 4042 | CharacterVector F = trimws(A, "b"); 4043 | // Output: "a b c" "a b c" "a b c" 4044 | 4045 | // -- Single Rcpp String object 4046 | 4047 | Rcpp::String G = trimws(B, "b"); 4048 | // Output: "a b c" 4049 | 4050 | 4051 | // -- Matrix 4052 | 4053 | CharacterMatrix H = trimws(C, "b"); 4054 | // Output: 4055 | // [,1] [,2] 4056 | // [1,] "a b c" "a b c" 4057 | // [2,] "a b c" "a b c" 4058 | // [3,] "a b c" "a b c 4059 | ``` 4060 | 4061 | ---- 4062 | 4063 | ## Statistical Distributions {#stat-dist} 4064 | 4065 | - There exists two approaches for working with statistical distribution functions 4066 | within Rcpp. The approaches differ on how the result is returned. Specifically, 4067 | statistical distributions within the `Rcpp::` namespace return type 4068 | `NumericVector` whereas functions within the `R::` namespace return a single 4069 | `double` scalar value. 4070 | 4071 | - For drawing large samples with fixed distribution parameters, sampling under 4072 | one should sample under the `Rcpp::` namespace to obtain a `NumericVector`. 4073 | There is an added benefit to working under this scheme of having default 4074 | parameters for log probability and lower tail sampling akin to traditional R 4075 | versions. 4076 | 4077 | - For drawing samples with changing distribution parameters, sampling under 4078 | the `R::` namespace with a `for` loop is perferred as parameters for 4079 | each draw can be customized. 4080 | 4081 | 4082 | ### Discrete Distributions {#discrete-dist} 4083 | 4084 | #### Binomial Distribution {#bin-dist} 4085 | 4086 | | | 4087 | |:------------------------------------------------| 4088 | | **dbinomial(X, size, prob, log_p)** | 4089 | | **pbinomial(Q, size, prob, lower_tail, log_p)** | 4090 | | **qbinomial(P, size, prob, lower_tail, log_p)** | 4091 | | **rbinomial(n, size, prob)** | 4092 | 4093 | 4094 | ```{Rcpp rcpp_bin_dist} 4095 | // Consider X ~ Bin(n = 100, p = 0.5) 4096 | 4097 | IntegerVector xx = IntegerVector::create(46, 47, 48, 49, 50, 51, 52, 53, 54); 4098 | 4099 | // Vector returns 4100 | NumericVector densities = Rcpp::dbinom(xx, 100, .5, false) 4101 | NumericVector probs = Rcpp::pbinom(xx, 100, .5, true, false); 4102 | NumericVector qvals = Rcpp::qbinom(probs, 100, .5, true, false); 4103 | NumericVector rsamples = Rcpp::rbinom(20, 100, .5); 4104 | 4105 | // Scalar Returns 4106 | double dval = R::dbinom(46, 100, .5, false); 4107 | double pval = R::pbinom(46, 100, .5, true, false); 4108 | double qval = R::qbinom(0.242, 100, .5, true, false); 4109 | int rdraw = R::rbinom(46, 100); 4110 | ``` 4111 | 4112 | 4113 | #### Geometric Distribution {#geo-dist} 4114 | 4115 | | | 4116 | |:--------------------------------------| 4117 | | **dgeom(X, prob, log_p)** | 4118 | | **pgeom(Q, prob, lower_tail, log_p)** | 4119 | | **qgeom(P, prob, lower_tail, log_p)** | 4120 | | **rgeom(n, prob)** | 4121 | 4122 | 4123 | ```{Rcpp rcpp_geo_dist} 4124 | // Consider X ~ Geom(p = 0.25) 4125 | IntegerVector xx = seq_len(5); 4126 | 4127 | // Vector returns 4128 | NumericVector densities = Rcpp::dgeom(xx, .25, false) 4129 | NumericVector probs = Rcpp::pgeom(xx, .25, true, false); 4130 | IntegerVector qvals = Rcpp::qgeom(probs, .25, true, false); 4131 | IntegerVector rsamples = Rcpp::rgeom(20, .25); 4132 | 4133 | // Scalar Returns 4134 | double dval = R::dgeom(2, .25, false); 4135 | double pval = R::pgeom(2, .25, true, false); 4136 | int qval = R::qgeom(0.578125, .25, true, false); 4137 | int rdraw = R::rgeom(.25); 4138 | ``` 4139 | 4140 | #### Hypergeometric Distribution {#hypergeo-dist} 4141 | 4142 | | | 4143 | |:-------------------------------------------| 4144 | | **dhyper( X, m, n, k, log_p)** | 4145 | | **phyper( Q, m, n, k, lower_tail, log_p)** | 4146 | | **qhyper( P, m, n, k, lower_tail, log_p)** | 4147 | | **rhyper(nn, m, n, k)** | 4148 | 4149 | 4150 | ```{Rcpp rcpp_hypergeo_dist} 4151 | // Consider X ~ Hypergeo(m = 10, n = 7, k = 8) 4152 | IntegerVector xx = IntegerVector::create(3, 4, 5, 6, 7); 4153 | 4154 | // Vector returns 4155 | NumericVector densities = Rcpp::dhyper(xx, 10, 7, 8, false) 4156 | NumericVector probs = Rcpp::phyper(xx, 10, 7, 8, true, false); 4157 | NumericVector qvals = Rcpp::qhyper(probs, 10, 7, 8, true, false); 4158 | NumericVector rsamples = Rcpp::rhyper(20, 10, 7, 8); 4159 | 4160 | // Scalar Returns 4161 | double dval = R::dhyper(46, 10, 7, 8, false); 4162 | double pval = R::phyper(46, 10, 7, 8, true, false); 4163 | int qval = R::qhyper(0.4193747, 10, 7, 8, true, false); 4164 | int rdraw = R::rhyper(10, 7, 8); 4165 | ``` 4166 | 4167 | #### Negative Binomial Distribution {#negbin-dist} 4168 | 4169 | | | 4170 | |:-------------------------------------------------| 4171 | | **dnbinomial(X, size, prob, log_p)** | 4172 | | **pnbinomial(Q, size, prob, lower_tail, log_p)** | 4173 | | **qnbinomial(P, size, prob, lower_tail, log_p)** | 4174 | | **rnbinomial(n, size, prob)** | 4175 | 4176 | 4177 | ```{Rcpp rcpp_nbin_dist} 4178 | // Consider X ~ NegBin(n = 100, p = 0.5) 4179 | IntegerVector xx = IntegerVector::create(46, 47, 48, 49, 50, 51, 52, 53, 54); 4180 | 4181 | // Vector returns 4182 | NumericVector densities = Rcpp::dnbinom(xx, 100, .5, false) 4183 | NumericVector probs = Rcpp::pnbinom(xx, 100, .5, true, false); 4184 | NumericVector qvals = Rcpp::qnbinom(probs, 100, .5, true, false); 4185 | NumericVector rsamples = Rcpp::rnbinom(20, 100, .5); 4186 | 4187 | // Scalar Returns 4188 | double dval = R::dnbinom(46, 100, .5, false); 4189 | double pval = R::pnbinom(46, 100, .5, true, false); 4190 | double qval = R::qnbinom(0.242, 100, .5, true, false); 4191 | int rdraw = R::rnbinom(46, 100); 4192 | ``` 4193 | 4194 | #### Poisson Distribution {#pois-dist} 4195 | 4196 | | | 4197 | |:----------------------------------------| 4198 | | **dpois(X, lambda, log_p)** | 4199 | | **ppois(Q, lambda, lower_tail, log_p)** | 4200 | | **qpois(P, lambda, lower_tail, log_p)** | 4201 | | **rpois(n, lambda)** | 4202 | 4203 | - Computes either the density (d), probability (p), quantile (q), or 4204 | a random (r) sample of a vector or scalar from a Poisson distribution. 4205 | 4206 | - When simulating a vector or scalar from a Poisson distribution, 4207 | the value returned is within the natural numbers (e.g. $0, 1, 2, \ldots , 42, \ldots , \mathbb{N}$). 4208 | 4209 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4210 | as follows: 4211 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4212 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4213 | 4214 | - Examples: 4215 | 4216 | ```{Rcpp rcpp_pois_dist} 4217 | // Consider X ~ Pois(4) 4218 | IntegerVector xx = seq_len(10); 4219 | 4220 | // Vector returns 4221 | NumericVector densities = Rcpp::dpois(xx, 4, false) 4222 | NumericVector probs = Rcpp::ppois(xx, 4, true, false); 4223 | NumericVector qvals = Rcpp::qpois(probs, 4, true, false); 4224 | NumericVector rsamples = Rcpp::rpois(20, 4); 4225 | 4226 | // Scalar Returns 4227 | double dval = R::dpois(46, 4, false); 4228 | double pval = R::ppois(46, 4, true, false); 4229 | double qval = R::qpois(0.242, 4, true, false); 4230 | int rdraw = R::rpois(46); 4231 | ``` 4232 | 4233 | ### Wilcox Distribution {#wilcox-dist} 4234 | 4235 | | | 4236 | |:-----------------------------------------| 4237 | | **dwilcox( X, m, n, log_p)** | 4238 | | **pwilcox( Q, m, n, lower_tail, log_p)** | 4239 | | **qwilcox( P, m, n, lower_tail, log_p)** | 4240 | | **rwilcox(nn, m, n)** | 4241 | 4242 | - Computes either the density (d), probability (p), quantile (q), or 4243 | a random (r) sample of a vector or scalar from a Wilcox distribution. 4244 | 4245 | - When simulating a vector or scalar from a Wilcox distribution, 4246 | the value returned is within the natural numbers (e.g. $0, 1, 2, \ldots , 42, \ldots , \mathbb{N}$). 4247 | 4248 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4249 | as follows: 4250 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4251 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4252 | 4253 | - Examples: 4254 | 4255 | 4256 | ### Wilcoxon Signed Rank Distribution {#signed-dist} 4257 | 4258 | | | 4259 | |:----------------------------------------| 4260 | | **dsignrank( X, n, log_p)** | 4261 | | **psignrank( Q, n, lower_tail, log_p)** | 4262 | | **qsignrank( P, n, lower_tail, log_p)** | 4263 | | **rsignrank(nn, n)** | 4264 | 4265 | 4266 | ### Continuous Distributions {#continuous-dist} 4267 | 4268 | #### Beta Distribution {#beta-dist} 4269 | 4270 | | | 4271 | |:------------------------------------------------| 4272 | | **dbeta(X, shape1, shape2, log_p)** | 4273 | | **pbeta(Q, shape1, shape2, lower_tail, log_p)** | 4274 | | **qbeta(P, shape1, shape2, lower_tail, log_p)** | 4275 | | **rbeta(n, shape1, shape2)** | 4276 | 4277 | - Computes either the density (d), probability (p), quantile (q), or 4278 | a random (r) sample of a vector or scalar from a Beta distribution. 4279 | 4280 | - When simulating a vector or scalar from a Beta distribution, 4281 | the value returned is within [0, 1]. 4282 | 4283 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4284 | as follows: 4285 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4286 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4287 | 4288 | - Examples: 4289 | 4290 | ```{Rcpp rcpp_beta_dist} 4291 | // Consider X ~ Beta(1,1) 4292 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4293 | 4294 | // Vector returns 4295 | NumericVector densities = Rcpp::dbeta(xx, 1.0, 1.0, false); 4296 | NumericVector probs = Rcpp::pbeta(xx, 1.0, 1.0, true, false); 4297 | NumericVector qvals = Rcpp::qbeta(probs, 1.0, 1.0, true, false); 4298 | NumericVector rsamples = Rcpp::rbeta(5, 1.0, 1.0); 4299 | 4300 | // Scalar Returns 4301 | double dval = R::dbeta(0.5, 1.0, 1.0, false); 4302 | double pval = R::pbeta(0.5, 1.0, 1.0, true, false); 4303 | double qval = R::qbeta(0.85, 1.0, 1.0, true, false); 4304 | double rdraw = R::rbeta(1.0, 1.0); 4305 | ``` 4306 | 4307 | 4308 | #### Cauchy Distribution {#cauchy-dist} 4309 | 4310 | | | 4311 | |:---------------------------------------------------| 4312 | | **dcauchy(X, location, scale, log_p)** | 4313 | | **pcauchy(Q, location, scale, lower_tail, log_p)** | 4314 | | **qcauchy(P, location, scale, lower_tail, log_p)** | 4315 | | **rcauchy(n, location, scale)** | 4316 | 4317 | - Computes either the density (d), probability (p), quantile (q), or 4318 | a random (r) sample of a vector or scalar from a Cauchy distribution. 4319 | 4320 | - When simulating a vector or scalar from a Cauchy distribution, 4321 | the value returned is within (-infty, infty). 4322 | 4323 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4324 | as follows: 4325 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4326 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4327 | 4328 | - Examples: 4329 | 4330 | ```{Rcpp rcpp_cauchy_dist} 4331 | // Consider X ~ Cauchy(loc = 0, scale = 1) 4332 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4333 | 4334 | // Vector returns 4335 | NumericVector densities = Rcpp::dcauchy(xx, 0.0, 1.0, false) 4336 | NumericVector probs = Rcpp::pcauchy(xx, 0.0, 1.0, true, false); 4337 | NumericVector qvals = Rcpp::qcauchy(probs, 0.0, 1.0, true, false); 4338 | NumericVector rsamples = Rcpp::rcauchy(20, 0.0, 1.0); 4339 | 4340 | // Scalar Returns 4341 | double dval = R::dcauchy(0.25, 0.0, 1.0, false); 4342 | double pval = R::pcauchy(0.25, 0.0, 1.0, true, false); 4343 | double qval = R::qcauchy(0.578, 0.0, 1.0, true, false); 4344 | double rdraw = R::rcauchy(0.0, 1.0); 4345 | ``` 4346 | 4347 | 4348 | #### Chi-square Distribution {#chisquare-dist} 4349 | 4350 | | | 4351 | |:-------------------------------------| 4352 | | **dchisq(X, df, log)** | 4353 | | **pchisq(Q, df, lower_tail, log_p)** | 4354 | | **qchisq(P, df, lower_tail, log_p)** | 4355 | | **rchisq(n, df)** | 4356 | 4357 | - Computes either the density (d), probability (p), quantile (q), or 4358 | a random (r) sample of a vector or scalar from a Chi-squared distribution. 4359 | 4360 | - When simulating a vector or scalar from a Chi-squared distribution, 4361 | the value returned is within [0, infty). 4362 | 4363 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4364 | as follows: 4365 | - `log_p = FALSE`, probabilities, densities are returned as log(p). 4366 | - `lower_tail = TRUE`, probabilities are calculated by P(X <= x) instead of P(X > x). 4367 | 4368 | - Examples: 4369 | 4370 | ```{Rcpp rcpp_chisq_dist} 4371 | // Consider X ~ X^2(df = 2) 4372 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4373 | 4374 | // Vector returns 4375 | NumericVector densities = Rcpp::dchisq(xx, 2, false) 4376 | NumericVector probs = Rcpp::pchisq(xx, 2, true, false); 4377 | NumericVector qvals = Rcpp::qchisq(probs, 2, true, false); 4378 | NumericVector rsamples = Rcpp::rchisq(20, 2); 4379 | 4380 | // Scalar Returns 4381 | double dval = R::dchisq(0.25, 2, false); 4382 | double pval = R::pchisq(0.5, 2, true, false); 4383 | double qval = R::qchisq(0.22, 2, true, false); 4384 | double rdraw = R::rchisq(2); 4385 | ``` 4386 | 4387 | #### Non-central Chi-square Distribution {#nchisquare-dist} 4388 | 4389 | | | 4390 | |:-------------------------------------------| 4391 | | **dnchisq(X, df, ncp, log_p)** | 4392 | | **pnchisq(Q, df, ncp, lower_tail, log_p)** | 4393 | | **qnchisq(P, df, ncp, lower_tail, log_p)** | 4394 | 4395 | - Computes either the density (d), probability (p), quantile (q), or 4396 | a random (r) sample of a vector or scalar from a Non-central Chi-squared 4397 | distribution. 4398 | 4399 | - When simulating a vector or scalar from a Non-central Chi-squared distribution, 4400 | the value returned is within $\left[0, \infty\right)$. 4401 | 4402 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4403 | as follows: 4404 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4405 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4406 | 4407 | - Examples: 4408 | 4409 | ```{Rcpp rcpp_nchisq_dist} 4410 | // Consider X ~ X^2(df = 2, ncp = 2.5) 4411 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4412 | 4413 | // Vector returns 4414 | NumericVector densities = Rcpp::dchisq(xx, 2, 2.5, false) 4415 | NumericVector probs = Rcpp::pchisq(xx, 2, 2.5, true, false); 4416 | NumericVector qvals = Rcpp::qchisq(probs, 2, 2.5, true, false); 4417 | 4418 | // Scalar Returns 4419 | double dval = R::dnchisq(0.25, 2, false); 4420 | double pval = R::pnchisq(0.5, 2, true, false); 4421 | double qval = R::qnchisq(0.22, 2, true, false); 4422 | ``` 4423 | 4424 | #### Exponential Distribution {#exp-dist} 4425 | 4426 | | | 4427 | |:-------------------------------------| 4428 | | **dexp(X, rate, log_p)** | 4429 | | **pexp(Q, rate, lower_tail, log_p)** | 4430 | | **qexp(P, rate, lower_tail, log_p)** | 4431 | | **rexp(n, rate)** | 4432 | 4433 | - Computes either the density (d), probability (p), quantile (q), or 4434 | a random (r) sample of a vector or scalar from an Exponential distribution under 4435 | the lambda parameterization: f(v) = lambda x exp(-lambda x v) 4436 | 4437 | - When simulating a vector or scalar from an Exponential distribution, the value returned 4438 | is within $\left[0, \infty\right)$. 4439 | 4440 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4441 | as follows: 4442 | - `rate = 1`, rate refers to the lambda parameter within an exponential 4443 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4444 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4445 | 4446 | - Examples: 4447 | 4448 | ```{Rcpp rcpp_exp_dist} 4449 | // Consider X ~ Exp(Rate = 1) 4450 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4451 | 4452 | // Vector returns 4453 | NumericVector densities = Rcpp::dexp(xx, 1.0, false) 4454 | NumericVector probs = Rcpp::pexp(xx, 1.0, true, false); 4455 | NumericVector qvals = Rcpp::qexp(probs, 1.0, true, false); 4456 | NumericVector rsamples = Rcpp::rexp(20, 1.0); 4457 | 4458 | // Scalar Returns 4459 | double dval = R::dexp(0.25, 2, false); 4460 | double pval = R::pexp(0.5, 2, true, false); 4461 | double qval = R::qexp(0.22, 2, true, false); 4462 | double rdraw = R::rexp(2); 4463 | ``` 4464 | 4465 | 4466 | #### F Distribution {#f-dist} 4467 | 4468 | | | 4469 | |:---------------------------------------| 4470 | | **df(X, df1, df2, log_p)** | 4471 | | **pf(Q, df1, df2, lower_tail, log_p)** | 4472 | | **qf(P, df1, df2, lower_tail, log_p)** | 4473 | | **rf(n, df1, df2)** | 4474 | 4475 | 4476 | - Computes either the density (d), probability (p), quantile (q), or 4477 | a random (r) sample of a vector or scalar from an F distribution. 4478 | 4479 | - When simulating a vector or scalar from an F distribution, the value returned 4480 | is within [0, infty). 4481 | 4482 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4483 | as follows: 4484 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4485 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4486 | 4487 | - Examples: 4488 | 4489 | ```{Rcpp rcpp_f_dist} 4490 | // Consider X ~ F(1, 5) 4491 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4492 | 4493 | // Vector returns 4494 | NumericVector densities = Rcpp::df(xx, 1.0, 5.0, false); 4495 | NumericVector probs = Rcpp::pf(xx, 1.0, 5.0 true, false); 4496 | NumericVector qvals = Rcpp::qf(probs, 1.0, 5.0, true, false); 4497 | NumericVector rsamples = Rcpp::rf(20, 1.0, 5.0); 4498 | 4499 | // Scalar Returns 4500 | double dval = R::df(0.25, 1.0, 5.0, false); 4501 | double pval = R::pf(0.5, 1.0, 5.0, true, false); 4502 | double qval = R::qf(0.49, 1.0, 5.0, true, false); 4503 | double rdraw = R::rf(1.0, 5.0); 4504 | ``` 4505 | 4506 | #### Non-central F Distribution {#nf-dist} 4507 | 4508 | 4509 | 4510 | #### Gamma Distribution {#gamma-dist} 4511 | 4512 | | | 4513 | |:----------------------------------------------| 4514 | | **dgamma(X, shape, rate, log_p)** | 4515 | | **pgamma(Q, shape, rate, lower_tail, log_p)** | 4516 | | **qgamma(P, shape, rate, lower_tail, log_p)** | 4517 | | **rgamma(n, shape, rate)** | 4518 | 4519 | - Computes either the density (d), probability (p), quantile (q), or 4520 | a random (r) sample of a vector or scalar from a Gamma distribution. 4521 | 4522 | - When simulating a vector or scalar from a Gamma distribution, the value returned 4523 | is within $\left[0, \infty\right)$. 4524 | 4525 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4526 | as follows: 4527 | - `rate = 1`, 4528 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4529 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4530 | 4531 | - Examples: 4532 | 4533 | ```{Rcpp rcpp_gamma_dist} 4534 | // Consider X ~ Gamma(1, 1) 4535 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4536 | 4537 | // Vector returns 4538 | NumericVector densities = Rcpp::dgamma(xx, 1.0, 1.0, false); 4539 | NumericVector probs = Rcpp::pgamma(xx, 1.0, 1.0, true, false); 4540 | NumericVector qvals = Rcpp::qgamma(probs, 1.0, 1.0, true, false); 4541 | NumericVector rsamples = Rcpp::rgamma(20, 1.0, 1.0); 4542 | 4543 | // Scalar Returns 4544 | double dval = R::dgamma(0.25, 1.0, 1.0, false); 4545 | double pval = R::pgamma(0.5, 1.0, 1.0, true, false); 4546 | double qval = R::qgamma(0.393, 1.0, 1.0, true, false); 4547 | double rdraw = R::rgamma(1.0, 1.0); 4548 | ``` 4549 | 4550 | ### Normal Distribution {#normal-dist} 4551 | 4552 | | | 4553 | |:------------------------------------------| 4554 | | **dnorm(X, mean, sd, log_p)** | 4555 | | **pnorm(Q, mean, sd, lower_tail, log_p)** | 4556 | | **qnorm(P, mean, sd, lower_tail, log_p)** | 4557 | | **rnorm(n, mean, sd)** | 4558 | 4559 | - Computes either the density (d), probability (p), quantile (q), or 4560 | a random (r) sample of a vector or scalar from a Normal distribution. 4561 | 4562 | - When simulating a vector or scalar from a Normal distribution, the value returned 4563 | is within $\left(-\infty, \infty\right)$. 4564 | 4565 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4566 | as follows: 4567 | - `MEAN = 0`, the mean of the distribution 4568 | - `SD = 1`, the standard derivation of the distribution 4569 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4570 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4571 | 4572 | - Examples: 4573 | 4574 | ```{Rcpp rcpp_normal_dist} 4575 | // Consider X ~ Norm(0, 1) 4576 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4577 | 4578 | // Vector returns 4579 | NumericVector densities = Rcpp::dnorm(xx, 0.0, 1.0, false); 4580 | NumericVector probs = Rcpp::pnorm(xx, 0.0, 1.0, true, false); 4581 | NumericVector qvals = Rcpp::qnorm(probs, 0.0, 1.0, true, false); 4582 | NumericVector rsamples = Rcpp::rnorm(20, 0.0, 1.0); 4583 | 4584 | // Scalar Returns 4585 | double dval = R::dnorm(0.25, 0.0, 1.0, false); 4586 | double pval = R::pnorm(0.95, 0.0, 1.0, true, false); 4587 | double qval = R::qnorm(1.96, 0.0, 1.0, true, false); 4588 | double rdraw = R::rnorm(0.0, 1.0); 4589 | ``` 4590 | 4591 | 4592 | ### Log Normal Distribution {#lognormal-dist} 4593 | 4594 | | | 4595 | |:-------------------------------------------------| 4596 | | **dlnorm(X, meanlog, sdlog, log_p)** | 4597 | | **plnorm(Q, meanlog, sdlog, lower_tail, log_p)** | 4598 | | **qlnorm(P, meanlog, sdlog, lower_tail, log_p)** | 4599 | | **rlnorm(n, meanlog, sdlog)** | 4600 | 4601 | - Computes either the density (d), probability (p), quantile (q), or 4602 | a random (r) sample of a vector or scalar from a Log Normal distribution. 4603 | 4604 | - When simulating a vector or scalar from a Log Normal distribution, the value returned 4605 | is within $\left[0,\infty\right)$. 4606 | 4607 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4608 | as follows: 4609 | - `meanlog = 0`, the log mean of the distribution 4610 | - `sdlog = 1`, the log standard derivation of the distribution 4611 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4612 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4613 | 4614 | - Examples: 4615 | 4616 | ```{Rcpp rcpp_lnorm_dist} 4617 | // Consider X ~ LogNorm(0, 1) 4618 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4619 | 4620 | // Vector returns 4621 | NumericVector densities = Rcpp::dlnorm(xx, 0.0, 1.0, false); 4622 | NumericVector probs = Rcpp::plnorm(xx, 0.0, 1.0, true, false); 4623 | NumericVector qvals = Rcpp::qlnorm(probs, 0.0, 1.0, true, false); 4624 | NumericVector rsamples = Rcpp::rlnorm(20, 0.0, 1.0); 4625 | 4626 | // Scalar Returns 4627 | double dval = R::dlnorm(0.25, 0.0, 1.0, false); 4628 | double pval = R::plnorm(0.5, 0.0, 1.0, true, false); 4629 | double qval = R::qlnorm(0.0452, 0.0, 1.0, true, false); 4630 | double rdraw = R::rlnorm(0.0, 1.0); 4631 | ``` 4632 | 4633 | ### Logistic Distribution {#logistic-dist} 4634 | 4635 | | | 4636 | |:--------------------------------------------------| 4637 | | **dlogis(X, location, scale, log_p)** | 4638 | | **plogis(Q, location, scale, lower_tail, log_p)** | 4639 | | **qlogis(P, location, scale, lower_tail, log_p)** | 4640 | | **rlogis(n, location, scale)** | 4641 | 4642 | - Computes either the density (d), probability (p), quantile (q), or 4643 | a random (r) sample of a vector or scalar from a Logistic distribution. 4644 | 4645 | - When simulating a vector or scalar from a Logistic distribution, the value returned 4646 | is within $\left(-\infty,\infty\right)$. 4647 | 4648 | - Under vectorization, e.g. `Rcpp::`, the default distribution parameters are 4649 | as follows: 4650 | - `location = 0`, the shift component of the distribution 4651 | - `scale = 1`, the dispersion parameter of the distribution that changes the spread e.g. if the scale is small, then the distribution is concentrated. 4652 | - `log_p = FALSE`, probabilities, densities are returned as $\log(p)$. 4653 | - `lower_tail = TRUE`, probabilities are calculated by $P(X \le x)$ instead of $P(X > x)$. 4654 | 4655 | - Examples: 4656 | 4657 | ```{Rcpp rcpp_logis_dist} 4658 | // Consider X ~ Logis(0, 1) 4659 | NumericVector xx = NumericVector::create(0.0, 0.25, 0.5, 0.75, 1.0); 4660 | 4661 | // Vector returns 4662 | NumericVector densities = Rcpp::dlogis(xx, 0.0, 1.0, false); 4663 | NumericVector probs = Rcpp::plogis(xx, 0.0, 1.0, true, false); 4664 | NumericVector qvals = Rcpp::qlogis(probs, 0.0, 1.0, true, false); 4665 | NumericVector rsamples = Rcpp::rlogis(20, 0.0, 1.0); 4666 | 4667 | // Scalar Returns 4668 | double dval = R::dlogis(0.25, 0.0, 1.0, false); 4669 | double pval = R::plogis(0.5, 0.0, 1.0, true, false); 4670 | double qval = R::qlogis(0.0452, 0.0, 1.0, true, false); 4671 | double rdraw = R::rlogis(0.0, 1.0); 4672 | ``` 4673 | 4674 | 4675 | ### Student's T Distribution {#t-dist} 4676 | 4677 | **rt()** 4678 | 4679 | ### Uniform Distribution {#unif-dist} 4680 | 4681 | **runif()** 4682 | 4683 | ### Weibull Distribution {#weibull-dist} 4684 | 4685 | **rweibull()** 4686 | 4687 | # Appendix 4688 | 4689 | 4690 | ## RTYPES 4691 | 4692 | | RTYPE | SEXPTYPE | Description | 4693 | |:------|:-------------|:----------------------------------------------------------| 4694 | | 0 | `NILSXP` | `NULL` | 4695 | | 1 | `SYMSXP` | symbols | 4696 | | 2 | `LISTSXP` | pairlists | 4697 | | 3 | `CLOSXP` | closures | 4698 | | 4 | `ENVSXP` | environments | 4699 | | 5 | `PROMSXP` | promises | 4700 | | 6 | `LANGSXP` | language objects | 4701 | | 7 | `SPECIALSXP` | special functions | 4702 | | 8 | `BUILTINSXP` | builtin functions | 4703 | | 9 | `CHARSXP` | internal character strings | 4704 | | 10 | `LGLSXP` | `logical` vectors | 4705 | | 13 | `INTSXP` | `integer` vectors | 4706 | | 14 | `REALSXP` | `numeric` vectors | 4707 | | 15 | `CPLXSXP` | `complex` vectors | 4708 | | 16 | `STRSXP` | `character` vectors | 4709 | | 17 | `DOTSXP` | dot-dot-dot object | 4710 | | 18 | `ANYSXP` | make "any" args work | 4711 | | 19 | `VECSXP` | `list` (`generic` vector) | 4712 | | 20 | `EXPRSXP` | `expression` vector | 4713 | | 21 | `BCODESXP` | byte code | 4714 | | 22 | `EXTPTRSXP` | external pointer | 4715 | | 23 | `WEAKREFSXP` | weak reference | 4716 | | 24 | `RAWSXP` | `raw` vector | 4717 | | 25 | `S4SXP` | `S4` classes not of simple type | 4718 | | 99 | `FUNSXP` | functions of type `CLOSXP`, `SPECIALSXP` and `BUILTINSXP` | 4719 | 4720 | - See also: 4721 | - [SEXPTYPEs on the official R Release documentation](https://cran.r-project.org/doc/manuals/r-release/R-ints.html#SEXPTYPEs) 4722 | - [The data types explained on the official R Release documentation](https://cran.r-project.org/doc/manuals/r-release/R-ints.html#The-_0027data_0027) 4723 | --------------------------------------------------------------------------------