-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathrcpp-api-docs.Rmd
4722 lines (3406 loc) · 147 KB
/
rcpp-api-docs.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Unofficial Rcpp API Documentation"
output:
pdf_document: default
html_document: default
date: '`r format(Sys.time(), "%F %T %z")`'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = FALSE)
```
**Warning: This post is a work in progress. It will periodically be updated
as time permits.**
# Introduction
The following **unofficial** API documentation for [Rcpp](http://rcpp.org) is based off some
personal notes and teaching materials that I have prepared over the years of
working with Rcpp. I've attempted to reformat the notes in the form of [Armadillo's API](http://arma.sourceforge.net/docs.html),
which I think are some of the best documentation out there for a C++ matrix library.
At some point, when the documentation becomes a bit more stable or if there is
larger contributor interest, I will likely attempt to merge this into the Rcpp
project so that a docs subdomain could hopefully be added to <http://rcpp.org>.
Please note: The post is written using [RMarkdown](http://rmarkdown.rstudio.com)
for maximum flexibility.
# API Documentation for Rcpp 0.12.11
## Preamble
- The goal of the API documentations are to provide a public facing concise
view of Rcpp features. As a result, the documentation will be somewhat long.
To help navigate the documentation, it has been split into different sections.
Furthermore, one should use the built in search functionality to search text
for keywords using either `CTRL` + `F` on Windows and Linux or `CMD` + `F` on
macOS.
- Presently, any contribution to this document can be made by a [pull request
(PRs)](https://github.com/coatless/rcpp-api/pulls) on GitHub.
- Please report any bugs to the [Rcpp Core Team](https://github.com/rcppcore/rcpp/issues).
## Overview
- [Vector, Matrix, List, DataFrame](#vmld)
- [Member functions](#member-functions)
- [Operators](#ops)
- [Dimensional Information](#dim-info)
- [Element Access](#elem-access)
- [Position Access](#position-access)
- [Categorical Access](#categorical-access)
- [Logical Access](#logical-access)
- [Subset Views](#subview)
- [Iterators](#iterators)
- [STL-style container functions](#stl-functions)
- [Static Member Functions](#static-members)
- [Sugar](#sugar)
- [Statistical Distributions](#stat-dist)
- [Exception Handling](#exception-handling)
- [External Exception Classes](#external-exception-clasess)
- [Internal Exception Classes](#internal-exception-clasess)
- [Simple Exceptions](#simple-exception)
- [Exceptions](#exception)
- [Advanced exceptions](#advanced-exception)
- Environment, Function, Language
- XPtr
- S4 classes / modules
------
## Vector, Matrix, List, and DataFrame Classes
| | |
|:----------------------------------------------------------------|:-------------------|
| [Vector<*RTYPE*>, NumericVector, IntegerVector, ...](#vector) | Vector class |
| [Matrix<*RTYPE*>, NumericMatrix, IntegerMatrix, ...](#matrix) | Matrix class |
| [List](#list) | List typedef |
| [DataFrame](#dataframe) | Data frame class |
| [RObject](#robject) | RObject class |
## Member functions
| | |
|:-------------------------------------------------|:-------------------------------------------------------------------|
| [Operators](#ops) | Mathematical (add, subtract, etc) and logical (inequalities) |
| [Dimensional Information](#dim-info) | Size attribute information |
| [Element Access](#elem-access) | Retrieving element values with and without bounds check |
| [Subset Views](#subview) | Subset data structures |
| [Iterators](#iterators) | Random access iterators |
| [STL-style Container Functions](#stl-functions) | Standard Library styled functions |
| [Static Member Functions](#static-members) | Set of member functions persistant across instances |
## Exception Handling
**[External Exception Classes](#external-exception-clasess)**
| | |
|------------------------------------|------------------------------|
| [`stop`](#stop) | Stop execution |
| [`warning`](#warning) | Send Warning to console |
**[Internal Exception Classes](#internal-exception-clasess)**
_[Simple Exceptions](#simple-exception)_
| | |
|-----------------------------------------------|--------------------------------|
| [`not_a_matrix`](#simple-exception) | Object is not a matrix |
| [`parse_error`](#simple-exception) | Unable to parse values |
| [`not_s4`](#simple-exception) | Not a valid S4 class |
| [`not_reference`](#simple-exception) | Object not a reference |
| [`not_initialized`](#simple-exception) | Object not initialized |
| [`no_such_slot`](#simple-exception) | S4 Object lacks slot |
| [`no_such_field`](#simple-exception) | Exception not used |
| [`not_a_closure`](#simple-exception) | Object not a closure |
| [`no_such_function`](#simple-exception) | No such function |
| [`unevaluated_promise`](#simple-exception) | Promise not yet evaluated |
_[Exceptions](#exception)_
| | |
|-----------------------------------------------|-----------------------------------|
| [`S4_creation_error`](#exception) | Error creating object of S4 class |
| [`reference_creation_error`](#exception) | Exception not used |
| [`no_such_binding`](#exception) | No such binding |
| [`binding_not_found`](#exception) | Binding not found |
| [`binding_is_locked`](#exception) | Binding is locked |
| [`no_such_namespace`](#exception) | No such namespace |
| [`function_not_exported`](#exception) | Function not exported |
| [`eval_error`](#exception) | Evaluation error |
_[Advanced exceptions](#advanced-exception)_
| | |
|-----------------------------------------------|---------------------------------|
| [`not_compatible`](#adv-exception) | Not a compatible transformation |
| [`index_out_of_bounds`](#adv-exception) | Request index is out of bounds |
## Sugar
**[Logical Operations](#sugar-logic-ops)**
| | |
|:-----------------------------|:---------------------------|
| [`ifelse`](#ifelse) | Vectorized If-else |
| [`is_false`](#isbool) | Is Value False? |
| [`is_true`](#isbool) | Is Value True? |
| [`any`](#any) | At Least One Value is True |
| [`all`](#all) | All Values Must be True |
**[Complex Operators](#sugar-complex-ops)**
| | |
|:------------------------------|:-----------------------------------|
| [`Re`](#complex-number) | Real Values of Complex Number |
| [`Im`](#complex-number) | Imaginary Values of Complex Number |
| [`Mod`](#complex-modulus) | Modulus (r) |
| [`Arg`](#complex-arg) | Arg (theta) |
| [`Conj`](#complex-conjugate) | Complex Conjugate |
**[Data Operations](#sugar-data-ops)**
| | |
|:----------------------------|:------------------------------|
| [`head`](#first-last-elems) | View the First _n_ Values |
| [`tail`](#first-last-elems) | View the Last _n_ Values |
| [`abs`](#abs) | Absolute Value |
| [`sqrt`](#sqrt) | Square Root |
| [`pow`](#pow) | Raise to the _n_^th^ Power |
| [`sum`](#sum) | Summation |
| [`sign`](#sign) | Extract the Sign of Values |
| [`diff`](#diff) | Lagged Difference |
| [`cumsum`](#carth) | Cumulative Sum |
| [`cumprod`](#carth) | Cumulative Product |
| [`cummin`](#cext) | Cumulative Minimum |
| [`cummax`](#cext) | Cumulative Maximum |
| [`sin`](#trig) | Sine |
| [`cos`](#trig) | Cosine |
| [`tan`](#trig) | Tangent |
| [`asin`](#trig) | Arc Sine |
| [`acos`](#trig) | Arc Cosine |
| [`atan`](#trig) | Arc Tangent |
| [`sinh`](#trig) | Hyperbolic Sine |
| [`cosh`](#trig) | Hyperbolic Cosine |
| [`tanh`](#trig) | Hyperbolic Tangent |
| [`log`](#logexp) | Natural Logarithms |
| [`exp`](#logexp) | Expoential |
| [`log10`](#logexp) | Base 10 Logarithm |
| [`log1p`](#logexp) | Natural Logarithm $log(1+x)$ |
| [`expm1`](#logexp) | $\exp(x) - 1$ |
| [`sample`](#sample) | Randomly sample values |
**[Rounding of Numbers](#sugar-rounding)**
| | |
|:-----------------------------------|:----------------------------------------------|
| [`ceiling`](#ceil),[`ceil`](#ceil) | Smallest integer greater than or equal to x |
| [`trunc`](#trunc) | Truncates the values in x toward 0 |
| [`floor`](#floor) | Largest integer less than or equal to x |
| [`round`](#round) | Round values to specified decimal place |
| [`signif`](#signif) | Rounds values to number of significant digits |
**[Finite, Infinite and NaN Detection](#sugar-nan)**
| | |
|:-----------------------------------|:-------------------------------------------|
| [`pre-defined`](#nanconstants) | Pre-defined NA/NaN/Inf Constants |
| [`is_na`](#missingness) | Detects if values are missing |
| [`is_nan`](#missingness) | Detects if values are not a number (`NaN`) |
| [`is_finite`](#finite) | Detects if value is finite |
| [`is_infinite`](#finite) | Detects if value is infinite |
| [`na_omit`](#na-omit) | Remove `NA` and `NaN` values |
| [`noNA`](#nona) | Assert that the object is `NA` free |
**[The Apply Family](#sugar-apply)**
| | |
|:----------------------|:----------------------------------------------------------------|
| [`sapply`](#sapply) | Apply a function to one input and store results in vector |
| [`lapply`](#lapply) | Apply a function to one input and store results in list |
| [`mapply`](#mapply) | Apply a function to multiple inputs and store results in vector |
**[Special Functions of Mathematics](#sugar-special-math)**
| | |
|:-----------------------------|:---------------------------|
| [`factorial`](#factorials) | Factorial |
| [`lfactorial`](#factorials) | Factorial Logarithm |
| [`choose`](#combinatorics) | Combination |
| [`lchoose`](#combinatorics) | Combination Logarithm |
| [`beta`](#beta) | Beta Function |
| [`lbeta`](#beta) | Natural Log Beta Function |
| [`gamma`](#gamma) | Gamma Function |
| [`lgamma`](#gamma) | Natural Log Gamma Function |
| [`psigamma`](#gamma-deriv) | General Gamma Derivative |
| [`digamma`](#gamma-deriv) | Second Gamma Derivative |
| [`trigamma`](#gamma-deriv) | Third Gamma Derivative |
| [`tetragamma`](#gamma-deriv) | Fourth Gamma Derivative |
| [`pentagamma`](#gamma-deriv) | Fifth Gamma Derivative |
**[Statistical Summaries](#sugar-stats)**
| | |
|:---------------------|:---------------------|
| [`min`](#minmax) | Minimum Value |
| [`max`](#minmax) | Maximum Value |
| [`range`](#range) | Range |
| [`mean`](#mean) | Mean Value |
| [`median`](#median) | Median Value |
| [`var`](#var) | Variance |
| [`sd`](#var) | Standard Deviation |
**[Special Operators](#sugar-special-ops)**
| | |
|:-----------------------|:-------------------------------------|
| [`rev`](#rev) | Reverse ordering of a vector |
| [`pmax`](#pext) | Parallel maximum value |
| [`pmin`](#pext) | Parallel minimum value |
| [`clamp`](#clamp) | Values between a minimum and maximum |
| [`which_max`](#which) | Index of the maximum value |
| [`which_min`](#which) | Index of the minimum value |
**[Uniqueness Operators](#sugar-unique-ops)**
| | |
|:------------------------------|:---------------------------------------------------------------|
| [`match`](#match) | Find indices of the first value in a separate vector |
| [`self_match`](#self-match) | Find indices of the first occurrence of each value in a vector |
| [`in`](#in) | Determine if a match was located for each element of _A_ in _B_|
| [`unique`](#unique) | Obtain the unique values |
| [`duplicated`](#unique) | Obtain a logical vector indicating the duplicate values |
| [`sort_unique`](#sort-unique) | Obtain the unique values and sort them |
| [`table`](#table) | Create a frequency table of occurrences |
**[Set Operations](#sugar-set-ops)**
| | |
|:--------------------------|:-----------------------------------------|
| [`setequal`](#setequal) | Equality of Set Values |
| [`intersect`](#intersect) | Intersection of Set Values |
| [`union_`](#union) | Union of Set Values |
| [`setdiff`](#setdiff) | Asymmetric Difference of Set Values |
**[Matrix Operations](#sugar-matrix-ops)**
| | |
|:---------------------------|:-----------------------------------------------|
| [`colSums`](#matrix-sum) | Column Sums of a Matrix |
| [`rowSums`](#matrix-sum) | Row Sums of a Matrix |
| [`colMeans`](#matrix-mean) | Column Means of a Matrix |
| [`rowMeans`](#matrix-mean) | Row Means of a Matrix |
| [`outer`](#outer) | Outer Product of Arrays on a Function |
| [`lower_tri`](#tri-mat) | Extract the _Lower_ Triangle Part of a Matrix |
| [`upper_tri`](#tri-mat) | Extract the _Upper_ Triangle Part of a Matrix |
| [`diag`](#diag) | Extract the Diagonal Portion of a Matrix |
| [`row`](#idx-mat) | Create a matrix of Row Indexes |
| [`col`](#idx-mat) | Create a matrix of Column Indexes |
**[Object Creation](#sugar-object-creation)**
| | |
|:--------------------|:-----------------------------------------------|
| [`cbind`](#cbind) | Create matrix by combing column vectors |
| [`seq_along`](#seq) | Generate an R index sequence given a vector |
| [`seq_len`](#seq) | Generate an R index sequence given an integer |
| [`rep`](#rep) | Replicate vector $N$ times |
| [`rep_each`](#rep) | Replicate each element in line $N$ times |
| [`rep_len`](#rep) | Replicate values until vector is of length $N$ |
**[String Operations](#sugar-string-ops)**
| | |
|:------------------------|:-----------------------------------------------------|
| [`collapse`](#collapse) | Collapse multiple strings into one string |
| [`trimws`](#trimws) | Trim leading and/or trailing whitespace from strings |
**[Statistical Distributions](#stat-dist)**
**[Discrete Distributions](#discrete-dist)**
| | |
|-----------------------------------|------------------------|
| [`p/d/q/rbinom`](#bin-dist) | Binomial |
| [`p/d/q/rgeom`](#geo-dist) | Geometric |
| [`p/d/q/rhyper`](#hypergeo-dist) | Hypergeometric |
| [`p/d/q/rnbinom`](#negbin-dist) | Negative Binomial |
| [`p/d/q/rpois`](#pois-dist) | Poisson |
| [`p/d/q/rwilcox`](#wilcox-dist) | Wilcoxon |
| [`p/d/q/rsignrank`](#signed-dist)| Wilcoxon Signed Rank |
**[Continuous Distributions](#continuous-dist)**
| | |
|------------------------------------|------------------------------|
| [`p/d/q/rbeta`](#beta-dist) | Beta |
| [`p/d/q/rcauchy`](#cauchy-dist) | Cauchy |
| [`p/d/q/rchisq`](#chisquare-dist) | Chi-square |
| [`p/d/qnchisq`](#nchisquare-dist) | Non-central Chi-square |
| [`p/d/q/rexp`](#exp-dist) | Exponential |
| [`p/d/q/rf`](#f-dist) | F |
| [`p/d/qnf`](#nf-dist) | Non-central F |
| [`p/d/q/rgamma`](#gamma-dist) | Gamma |
| [`p/d/q/rnorm`](#normal-dist) | Normal |
| [`p/d/q/rlnorm`](#lognormal-dist) | Log Normal |
| [`p/d/q/rlogis`](#logistic-dist) | Logistic |
| [`p/d/q/rt`](#t-dist) | Student's T |
| [`p/d/q/runif`](#unif-dist) | Uniform |
| [`p/d/q/rweibull`](#weibull-dist) | Weibull |
## Vector, Matrix, List, and DataFrame Classes {#vmld}
### Vector {#vector}
- The templated `Vector` class is a one dimensional array-like structure
providing storage for homogenous data types, with an
interface similar to that of `std::vector`. Being an implementation of
[policy-based design](https://en.wikipedia.org/wiki/Policy-based_design),
much of the behavior of `Vector` is determined by the policy classes it
inherits from
- `RObjectMethods`
- `StoragePolicy`
- `SlotProxyPolicy`
- `AttributeProxyPolicy`
- `NamesProxyPolicy`
as well as the CRTP base class `VectorBase`. This type is instantiated as
`Vector<RTYPE>`, where `RTYPE` is one of the following valid `SEXPTYPE`s:
- `REALSXP`
- `INTSXP`
- `CPLXSXP`
- `LGLSXP`
- `STRSXP`
- `VECSXP`
- `RAWSXP`
- `EXPRSXP`
- 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:
- `NumericVector` = `Vector<REALSXP>`
- `DoubleVector` = `Vector<REALSXP>`
- `RawVector` = `Vector<RAWSXP>`
- `IntegerVector` = `Vector<INTSXP>`
- `ComplexVector` = `Vector<CPLXSXP>`
- `LogicalVector` = `Vector<LGLSXP>`
- `CharacterVector` = `Vector<STRSXP>`
- `StringVector` = `Vector<STRSXP>`
- `GenericVector` = `Vector<VECSXP>`
- `List` = `Vector<VECSXP>`
- `ExpressionVector` = `Vector<EXPRSXP>`
- Within this documentation, the default type used will be `NumericVector` unless
another data type is required to show a specific feature.
- Constructors:
- `Vector()`
- `Vector(SEXP x)`
- `Vector(const int &size, const stored_type &u)`
- `Vector(const std::string &st)`
- `Vector(const char *st)`
- `Vector(const Vector &other)`
- `Vector(const int &size)`
- `Vector(const Dimension &dims)`
- `Vector(const Dimension &dims, const U &u)`
- `Vector(const Vector &other)`
- By default, the vectors constructed from dimensions will always be
initialized with all entries being zero (`0`) or an empty string (`""`).
- For the majority of cases, the interface being used is that of the R to C++
interface that relies upon the `Vector(SEXP x)` constructor, which establishes
a **pointer** to the underlying data. That is, the `Vector` object _points_ to
the memory location of the `SEXP` R object in order to avoid copying the data
into _C++_. The only exception to this rule is if the data passed is of a
different type in which case a deep copy is performed _before_ a pointer is
established. For example, if `numeric()` data is passed to `NumericVector`
the correct handoff occurs. However, if `integer()` data were to be passed to
a `NumericVector` a `clone()` would be made to type `numeric()` which has its
pointer then assigned to the `NumericMatrix`.
- Examples:
```{Rcpp rcpp_vector_ctor}
SEXP A;
NumericVector B(A); // from a SEXP
// create a vector of length 5 filled with 0
NumericVector C(5);
// Output: 0 0 0 0 0
// construct a filled vector of size 3 with 2.0
NumericVector D = NumericVector(3, 2.0);
// Output: 2 2 2
// initialize empty numeric vector of size 5
NumericVector D2 = no_init(5);
// fill vector with 3.0
D2.fill(3.0);
// Output: 3 3 3 3 3
// cloning (deep copy)
NumericVector E = clone(D);
// Output: 2 2 2
```
- See also:
- [Vector Class doxygen documentation](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1Vector.html)
- [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef)
------
### Matrix {#matrix}
- The main class for matrices is the templated `Matrix` class, which derives from
a combination of both the `Vector` and `MatrixBase` types. Like the `Vector`
class, `Matrix` uses the policy-based design pattern to manage the lifetime of
its undelying `SEXP` via the template parameter `StoragePolicy`, which
uses the `PreserveStorage` policy class by default. Matrices are
instantiated as `Matrix<RTYPE>`, where the value `RTYPE` is one of the
following `SEXPTYPE`s:
- `REALSXP`
- `INTSXP`
- `CPLXSXP`
- `LGLSXP`
- `STRSXP`
- `VECSXP`
- `RAWSXP`
- `EXPRSXP`
- 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`
namespace:
- `NumericMatrix` = `Matrix<REALSXP>`
- `RawMatrix` = `Matrix<RAWSXP>`
- `IntegerMatrix` = `Matrix<INTSXP>`
- `ComplexMatrix` = `Matrix<CPLXSXP>`
- `LogicalMatrix` = `Matrix<LGLSXP>`
- `CharacterMatrix` = `Matrix<STRSXP>`
- `StringMatrix` = `Matrix<STRSXP>`
- `GenericMatrix` = `Matrix<VECSXP>`
- `ListMatrix` = `Matrix<VECSXP>`
- `ExpressionMatrix` = `Matrix<EXPRSXP>`
- Within this documentation, the default type used will be `NumericMatrix` unless
another data type is required to show a specific feature.
- Constructors:
- `Matrix()`
- `Matrix(SEXP x)`
- `Matrix(const int& nrows_, const int& ncols)`
- `Matrix(const int& nrows_, const int& ncols, Iterator start)`
- `Matrix(const int& n)`
- `Matrix(const Matrix& other)`
- By default, the matrices constructed from dimensions will always be
initialized with all entries being zero (`0`) or empty strings (`""`)
- For the majority of cases, the interface being used is that of the R to C++
interface that relies upon the `Matrix(SEXP x)` constructor, which establishes
a **pointer** to the underlying data. That is, the `Matrix` object _points_ to
the memory location of the `SEXP` R object in order to avoid copying the data
into _C++_. The only exception to this rule is if the data passed is of a
different type in which case a deep copy is performed _before_ a pointer is
established. For example, if `numeric()` data is passed to `NumericMatrix`
the correct handoff occurs. However, if `integer()` data were to be passed to
a `NumericMatrix` a `clone()` would be made to type `numeric()` which has its
pointer then assigned to the `NumericMatrix`.
- Examples:
```{Rcpp rcpp_matrix_ctor}
SEXP A;
NumericMatrix B(A); // from a SEXP
// create a square matrix (all elements set to 0.0)
NumericMatrix C(2);
// Output:
// 0 0
// 0 0
// of a given size (all elements set to 0.0)
NumericMatrix D(2, 3);
// Output:
// 0 0 0
// 0 0 0
// of a given size with dimensions (all elements set to 0.0)
NumericMatrix D2(Dimension(3, 2));
// Output:
// 0 0
// 0 0
// 0 0
// initialize empty numeric matrix
NumericMatrix D3 = no_init(2, 1);
// fill matrix with 3.0
D3.fill(3.0);
// Output:
// 3.0
// 3.0
// fill matrix using a vector
NumericVector E = NumericVector(15, 2.0);
NumericMatrix F = NumericMatrix(3, 5, E.begin());
// Output:
// 2 2 2 2 2
// 2 2 2 2 2
// 2 2 2 2 2
// cloning (explicit deep copy)
NumericMatrix G = clone(F);
```
- See also:
- [`Matrix` Class doxygen documentation](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1Matrix.html)
- [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef)
### List {#list}
- The `List` data structure is a `typedef` of templated `Vector` class based
on the `RTYPE` of `VECSXP` that provides heterogenous storage class. As
a result, the `List` class acts as a generic storage object that can
simultaneously hold multiple different `RTYPE` structures.
- Constructors:
- `List()`
- `List(SEXP x)`
- `List(const int &size, const stored_type &u)`
- `List(const std::string &st)`
- `List(const char *st)`
- `List(const Vector &other)`
- `List(const int &size)`
- `List(const Dimension &dims)`
- `List(const Dimension &dims, const U &u)`
- `List(const Vector &other)`
- Unlike the `Vector` class, the `List` constructed from dimensions will have a
`NULL` value set for each element unless a value is otherwise assigned.
- Examples:
```{Rcpp rcpp_list_ctor}
SEXP A;
List B(A); // from a SEXP
// create an empty List of size 2
List C(2);
// Output:
// [[1]]
// NULL
// [[2]]
// NULL
// construct List of size 3 with one element containing 2.0
List D = List(3, 2.0);
// Output:
// [[1]]
// [1] 2
// [[2]]
// [1] 2
// [[3]]
// [1] 2
// initialize empty list of size 3
List D2 = no_init(3);
// fill list one element equal to 3.0
D2.fill(3.0);
// Output:
// [[1]]
// [1] 3
// [[2]]
// [1] 3
// [[3]]
// [1] 3
// cloning (deep copy)
List E = clone(D);
// Output:
// [[1]]
// [1] 2
// [[2]]
// [1] 2
// [[3]]
// [1] 2
// Create a named list
NumericVector F = NumericVector::create(1.2, 3.5);
CharacterVector G = CharacterVector::create("a", "b", "c");
LogicalVector H = LogicalVector::create(true, false, false, true);
// Create named list
List F = List::create(Named("v1") = F,
Named("v2") = G,
_["v3"] = H); // Shorthand for Named("V3")
// Output:
// $v1
// [1] 1.2 3.5
// $v2
// [1] "a" "b" "c"
// $v3
// [1] TRUE FALSE FALSE TRUE
```
- See also:
- [`Vector`](#vector)
- [Vector Class doxygen documentation](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1Vector.html)
- [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef)
### DataFrame {#dataframe}
- The `DataFrame` data structure is a typedef of the `DataFrame_Impl` class,
which is a special extension of the templated `Vector` class
that allows for a collection of heterogenous `Vector`'s of the same length.
As the crux of the implementation of is
[policy-based design](https://en.wikipedia.org/wiki/Policy-based_design) focused,
much of the behavior of `DataFrame` is determined by the policy classes it
inherits from
- `RObjectMethods`
- `StoragePolicy`
- `SlotProxyPolicy`
- `AttributeProxyPolicy`
- `NamesProxyPolicy`
as well as the CRTP base class `VectorBase`.
- Constructors:
- `DataFrame()`
- `DataFrame(SEXP x)`
- `DataFrame(const DataFrame &other)`
- `DataFrame(const T &obj)`
- **Caveat:** All `DataFrame` columns _must_ be named. Failure to name the columns
will result in the run time error of:
> not compatible with STRSXP
since Rcpp uses an internal call to _R_ to create the `DataFrame`.
- Examples:
```{Rcpp rcpp_dataframe_ctor}
SEXP A;
DataFrame B(A); // from a SEXP
// Create Data
NumericVector C = NumericVector::create(5.8, 9.1, 3.2);
CharacterVector D = CharacterVector::create("a", "b", "c");
LogicalVector E = LogicalVector::create(true, false, false);
// Create a new dataframe
DataFrame G = DataFrame::create(Named("C") = C,
_["D"] = D, // shorthand for Named("D")
Named("E") = E);
```
- See also:
- [`Vector`](#vector)
- [DataFrame `typedef`](http://dirk.eddelbuettel.com/code/rcpp/html/DataFrame_8h.html)
- [`DataFrame_Impl` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1DataFrame__Impl.html)
- [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef)
### RObject {#robject}
- The `RObject` data structure is a typedef of the `RObject_Impl` class. Principally,
the class can be viewed as the glue of Rcpp due to [policy-based design](https://en.wikipedia.org/wiki/Policy-based_design)
principles. In turn, the `RObject` class really acts as a "shell" that stores
properties of the following policies:
- `PreserveStorage`: Member functions that provide the `SEXP` _R_ object
alongside ways to modify and update the object.
- `SlotProxyPolicy`: Member functions related to _only_ manipulating S4
objects.
- `AttributeProxyPolicy`: Member functions that modify attribute information
of the _R_ object.
- `RObjectMethods`: Member functions that provide descriptors of the _R_
object such as type, object oriented programming (S3/S4) system, and
`NULL` status.
- Constructors:
- `RObject()`
- `RObject(const RObject &other)`
- `RObject(const GenericProxy<Proxy> &proxy)`
- Examples:
```{Rcpp robject_example}
// Extract attribute information via AttributeProxyPolicy
RObject A;
RObject B = A.attr("dim");
```
- See also:
- [Modern C++ Design](http://en.wikipedia.org/wiki/Modern_C++_Design)
- [`RObject_Impl` class](http://dirk.eddelbuettel.com/code/rcpp/html/RObject_8h.html)
- [`RObjectMethods` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1RObjectMethods.html)
- [`StoragePolicy` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1StoragePolicy.html)
- [`SlotProxyPolicy` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1SlotProxyPolicy.html)
- [`AttributeProxyPolicy` class](http://dirk.eddelbuettel.com/code/rcpp/html/classRcpp_1_1AttributeProxyPolicy.html)
- [`typedef` at cppreference.com](http://en.cppreference.com/w/cpp/language/typedef)
## Member Functions {#member-functions}
### Operators {#ops}
- Operators allow for operations to take place between two different `Vector` or `Matrix` objects.
The operations are defined to works in an element-wise fashion where applicable.
- Viable mathematical operations that are able to be performed.
| Operation | Definition | Vector-Vector | Vector-Scalar | Vector-Matrix | Matrix - Matrix | Matrix - Scalar |
|:---------:|:------------------:|:-------------:|:--------------:|:-------------:|:---------------:|:---------------:|
| + | Addition | Yes | Yes | No | No | Yes |
| - | Subtraction | Yes | Yes | No | No | Yes |
| / | Division | Yes | Yes | No | No | Yes |
| * | Multiplication | Yes | Yes | No | No | Yes |
- Logical Operations
| Operation | Definition | Vector-Vector | Vector-Scalar | Vector-Matrix | Matrix - Matrix | Matrix - Scalar |
|:---------:|:-------------------------:|:-------------:|:--------------:|:---------------:|:---------------:|:---------------:|
| == | Equality | Yes | Yes | No | No | Yes |
| != | Non-equality | Yes | Yes | No | No | Yes |
| >= | Greater than or equal to | Yes | Yes | No | No | Yes |
| <= | Less than or equal to | Yes | Yes | No | No | Yes |
| < | Less than | Yes | Yes | No | No | Yes |
| > | Greater than | Yes | Yes | No | No | Yes |
| ! | Negate | Yes | Yes | No | No | Yes |
- Examples:
```{Rcpp sugar_math_ops}
// Sample data
NumericVector A = NumericVector::create(1, 2, 3, 4);
NumericVector B = NumericVector::create(2, 3, 4, 5);
// --- Addition
// Add a vector and scalar
NumericVector H = A + 2.0;
// Output: 3 4 5 6
// Add a vector and another vector
NumericVector I = A + B;
// Output: 3 5 7 9
// --- Subtraction
// Subtract a scalar from a vector
NumericVector J = 2.0 - A;
// Output: 1 0 -1 -2
// Subtract vectors
NumericVector K = A - B;
// Output: -1 -1 -1 -1
// --- Multiplication
// Multiple by scalar
NumericVector L = 3 * A;
// Output: 3 6 9 12
// Multiple Vectors
NumericVector M = A * B;
// Output: 2 6 12 20
// --- Division
// Divide by scalar
NumericVector L = 1 / A;
// Output: 1.0000000 0.5000000 0.3333333 0.2500000
// Divide Vectors
NumericVector M = A / B;
// Output: 0.5000000 0.6666667 0.7500000 0.8000000
// --- All together
NumericVector res = 3.0 * A - 1.0 / B + A + B + 5.0;
// Output: 10.50000 15.66667 20.75000 25.80000
```
### Dimensional Information {#diminfo}
| | |
|:----------------------|:---------------------------------------------|
| `.nrow()`,`.rows()` | number of rows in a `Matrix`, `DataFrame` |
| `.ncol()`,`.cols()` | number of columns in a `Matrix`, `DataFrame` |
| `.size()`,`.length()` | number of items in a `Matrix`, `Vector` |
- Return type is that of an `int`, `unsigned int`, or `R_xlen_t`
- Note: As of Rcpp 0.13.0, new size attribute accessors were added to the
`DataFrame` class that mimick those available in `Matrix`. Previously, to
obtain the number of columns, one would have to use the `.size()` or `.length()`
member function. In addition, the number of observations previously had to
be obtained by `.nrows()`.
- Examples:
```{Rcpp dimensional_info}
// --- Vector Example
NumericVector X(3);
int nelem = X.size(); // Output: 3
int nlens = X.length(); // Output: 3
Rcout << "Vector X has " << nelem << " elements." << std::endl;
// --- Matrix Example
NumericMatrix X(4,5);
int rows = X.nrow(); // Output: 4
int cols = X.ncols(); // Output: 5
int elems = X.size(); // Output: 20
Rcout << "Matrix Y has " << rows << " rows and " << cols << " columns." << std::endl;
```
### Element Access {#elem-access}
- Described within this section is the ability to access elements using
the position, categorical, and logical indexing systems.
- The access system provides two retrieval methods for all classes
that differ in computational time to obtain values from objects.
- The preferred method to access elements is `()`, which that takes slightly
longer due to a bounds check being performed that verifies whether the
requested element is within the access scope. Furthermore, if the
requested element is out of bounds, an exception is raised and the program
stops.
- The other method uses `[]`, which does _not_ perform a bounds check and
assumes that the access scope is valid. If an element is out of bounds,
the behavior exhibited will be undefined and may cause havoc with later
parts of a procedure. Only use this form of accessor if the procedure has
been thoroughly tested and debugged.
- Note: Using accessors without a bounds check is **not** recommended unless
the code has been thoroughly tested as undefined behavior (UB) may emerge. UB
is very problematic.
#### Position Access {#position-access}
- Access a single element or object using a positional index.
- `(i)` provides the *i*th element or object in addition to performing a
bounds check that ensures the requested index is a valid location.
- `[i]` similar to the previous case, but does so *without* a bounds check.
- `at(i,j)` provides the *i,j*th element of a `Matrix` with a bounds check.
- `(i,j)` provides the *i,j*th element of a `Matrix` *without* a bounds check.
- **Caveat:** Using either `[i]` or `(i)` on `List` and `DataFrame`,
provides the object (e.g. `Vector`) at position *i* whereas the use on
`Vector` or `Matrix` will provide a scalar element (e.g. `double`).
- Note: Unlike _R_, there is no `[]` subset operator for matrices with _C++_.
The reason for the lack of `operator[]` relates to a fundamental design choice
made by the creators of C++ related to the presence of the
[`operator,`](http://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator).
In essence, after the complete evaluation of the first coordinate `x` and disposal
of the results, only then is the second coordinate `y` able to be evaluated.
Unfortunately, this yields the following `-Wall` issue:
> left operand of comma operator has no effect.
Therefore, the only viable matrix subset operators within C++ are `operator()` and `operator at()` provide subset operations.
- Examples:
```{Rcpp position_access}
// Create data
NumericVector A = NumericVector::create(1, 2, 3, 4);
CharacterVector C = CharacterVector::create("B", "D", "E", "F");
// --- Vector
// Retrieve the first value from A. (C++ indices start at 0 not 1!)
double a = A(0);
// Output: 1
// Modify the last value using unbound accessor
// Warning: Make sure the point is valid!
A[3] = 5;
// --- Matrix
// Create matrix with elements in A
NumericMatrix B(2, 2, A.begin());
// Output:
// 1 3
// 2 5
// Extract Value at 2, 1
double val_r1c0 = B(1, 0);
// Output: 2
// Modify value at 1, 2
B(0, 1) = 4;
// Output:
// 1 4
// 2 5
// The following shows a bounds throw error
// B.at(1, 2) = 4;
// --- List
// Create a List
List D = List::create(Named("A") = A,
_["C"] = C); // shorthand for Named("C")
// Extract A from List
NumericVector E = D[0];
double val2 = E[1];
// Output: 2
// Extract B from List
CharacterVector F = D[1];
// --- Data Frame
// Create a DataFrame
DataFrame G = DataFrame::create(Named("A") = A,
_["C"] = C); // shorthand for Named("C")
// Extract A from DataFrame
NumericVector E = DF[0];
```
#### Categorical Access {#categorical-access}
- Access element by name within a `Vector`, `List`, or `DataFrame`.