This repository has been archived by the owner on Aug 20, 2022. It is now read-only.
forked from hadley/adv-r
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rcpp.Rmd
1269 lines (910 loc) · 49.3 KB
/
Rcpp.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
# High performance functions with Rcpp {#rcpp}
```{r setup, include = FALSE}
source("common.R")
source("performance-microbenchmark.R")
options("microbenchmark.unit" = "us")
```
Sometimes R code just isn't fast enough. You've used profiling to figure out where your bottlenecks are, and you've done everything you can in R, but your code still isn't fast enough. In this chapter you'll learn how to improve performance by rewriting key functions in C++. This magic comes by way of the [Rcpp](http://www.rcpp.org/) package, a fantastic tool written by Dirk Eddelbuettel and Romain Francois (with key contributions by Doug Bates, John Chambers, and JJ Allaire). Rcpp makes it very simple to connect C++ to R. While it is _possible_ to write C or Fortran code for use in R, it will be painful by comparison. Rcpp provides a clean, approachable API that lets you write high-performance code, insulated from R's arcane C API. \index{Rcpp} \index{C++}
Typical bottlenecks that C++ can address include:
* Loops that can't be easily vectorised because subsequent iterations depend
on previous ones.
* Recursive functions, or problems which involve calling functions millions of
times. The overhead of calling a function in C++ is much lower than that in
R.
* Problems that require advanced data structures and algorithms that R doesn't
provide. Through the standard template library (STL), C++ has efficient
implementations of many important data structures, from ordered maps to
double-ended queues.
The aim of this chapter is to discuss only those aspects of C++ and Rcpp that are absolutely necessary to help you eliminate bottlenecks in your code. We won't spend much time on advanced features like object oriented programming or templates because the focus is on writing small, self-contained functions, not big programs. A working knowledge of C++ is helpful, but not essential. Many good tutorials and references are freely available, including <http://www.learncpp.com/> and <http://www.cplusplus.com/>. For more advanced topics, the _Effective C++_ series by Scott Meyers is a popular choice. You may also enjoy Dirk Eddelbuettel's [_Seamless R and C++ integration with Rcpp_](http://www.springer.com/statistics/computational+statistics/book/978-1-4614-6867-7), which goes into much greater detail into all aspects of Rcpp.
##### Outline
* [Getting started with C++](#rcpp-intro) teaches you how to write C++ by
converting simple R functions to their C++ equivalents. You'll learn how
C++ differs from R, and what the key scalar, vector, and matrix classes
are called.
* [Using sourceCpp](#sourceCpp) shows you how to use `sourceCpp()` to load
a C++ file from disk in the same way you use `source()` to load a file of
R code.
* [Attributes & other classes](#rcpp-classes) discusses how to modify
attributes from Rcpp, and mentions some of the other important classes.
* [Missing values](#rcpp-na) teaches you how to work with R's missing values
in C++.
* [Rcpp sugar](#rcpp-sugar) discusses Rcpp "sugar", which allows you to
avoid loops in C++ and write code that looks very similar to vectorised R
code.
* [The STL](#stl) shows you how to use some of the most important data
structures and algorithms from the standard template library, or STL,
built-in to C++.
* [Case studies](#rcpp-case-studies) shows two real case studies where
Rcpp was used to get considerable performance improvements.
* [Putting Rcpp in a package](#rcpp-package) teaches you how to add C++ code
to a package.
* [Learning more](#rcpp-more) concludes the chapter with pointers to
more resources to help you learn Rcpp and C++.
##### Prerequistes
All examples in this chapter need version 0.10.1 or above of the `Rcpp` package. This version includes `cppFunction()` and `sourceCpp()`, which makes it very easy to connect C++ to R. Install the latest version of Rcpp from CRAN with `install.packages("Rcpp")`.
You'll also need a working C++ compiler. To get it:
* On Windows, install [Rtools](http://cran.r-project.org/bin/windows/Rtools/).
* On Mac, install Xcode from the app store.
* On Linux, `sudo apt-get install r-base-dev` or similar.
## Getting started with C++ {#rcpp-intro}
`cppFunction()` allows you to write C++ functions in R: \indexc{cppFunction()}
```{r add, cache = TRUE}
library(Rcpp)
cppFunction('int add(int x, int y, int z) {
int sum = x + y + z;
return sum;
}')
# add works like a regular R function
add
add(1, 2, 3)
```
When you run this code, Rcpp will compile the C++ code and construct an R function that connects to the compiled C++ function. We're going to use this simple interface to learn how to write C++. C++ is a large language, and there's no way to cover it all in just one chapter. Instead, you'll get the basics so that you can start writing useful functions to address bottlenecks in your R code.
The following sections will teach you the basics by translating simple R functions to their C++ equivalents. We'll start simple with a function that has no inputs and a scalar output, and then get progressively more complicated:
* Scalar input and scalar output
* Vector input and scalar output
* Vector input and vector output
* Matrix input and vector output
### No inputs, scalar output
Let's start with a very simple function. It has no arguments and always returns the integer 1:
```{r one-r}
one <- function() 1L
```
The equivalent C++ function is:
```cpp
int one() {
return 1;
}
```
We can compile and use this from R with `cppFunction`
```{r one-cpp, eval = TRUE, cache = TRUE}
cppFunction('int one() {
return 1;
}')
```
This small function illustrates a number of important differences between R and C++:
* The syntax to create a function looks like the syntax to call a function;
you don't use assignment to create functions as you do in R.
* You must declare the type of output the function returns. This function
returns an `int` (a scalar integer). The classes for the most common types
of R vectors are: `NumericVector`, `IntegerVector`, `CharacterVector`, and
`LogicalVector`.
* Scalars and vectors are different. The scalar equivalents of numeric,
integer, character, and logical vectors are: `double`, `int`, `String`, and
`bool`.
* You must use an explicit `return` statement to return a value from a
function.
* Every statement is terminated by a `;`.
### Scalar input, scalar output
The next example function implements a scalar version of the `sign()` function which returns 1 if the input is positive, and -1 if it's negative:
```{r sign, cache = TRUE}
signR <- function(x) {
if (x > 0) {
1
} else if (x == 0) {
0
} else {
-1
}
}
cppFunction('int signC(int x) {
if (x > 0) {
return 1;
} else if (x == 0) {
return 0;
} else {
return -1;
}
}')
```
In the C++ version:
* We declare the type of each input in the same way we declare the type of the
output. While this makes the code a little more verbose, it also makes it
very obvious what type of input the function needs.
* The `if` syntax is identical --- while there are some big differences between
R and C++, there are also lots of similarities! C++ also has a `while`
statement that works the same way as R's. As in R you can use `break` to
exit the loop, but to skip one iteration you need to use `continue` instead
of `next`.
### Vector input, scalar output
One big difference between R and C++ is that the cost of loops is much lower in C++. For example, we could implement the `sum` function in R using a loop. If you've been programming in R a while, you'll probably have a visceral reaction to this function!
```{r sum-r}
sumR <- function(x) {
total <- 0
for (i in seq_along(x)) {
total <- total + x[i]
}
total
}
```
In C++, loops have very little overhead, so it's fine to use them. In [STL](#stl), you'll see alternatives to `for` loops that more clearly express your intent; they're not faster, but they can make your code easier to understand.
```{r sum-cpp, cache = TRUE}
cppFunction('double sumC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total;
}')
```
The C++ version is similar, but:
* To find the length of the vector, we use the `.size()` method, which returns
an integer. C++ methods are called with `.` (i.e., a full stop).
* The `for` statement has a different syntax: `for(init; check; increment)`.
This loop is initialised by creating a new variable called `i` with value 0.
Before each iteration we check that `i < n`, and terminate the loop if it's
not. After each iteration, we increment the value of `i` by one, using the
special prefix operator `++` which increases the value of `i` by 1.
* In C++, vector indices start at 0. I'll say this again because it's so
important: __IN C++, VECTOR INDICES START AT 0__! This is a very common
source of bugs when converting R functions to C++.
* Use `=` for assignment, not `<-`.
* C++ provides operators that modify in-place: `total += x[i]` is equivalent to
`total = total + x[i]`. Similar in-place operators are `-=`, `*=`, and `/=`.
This is a good example of where C++ is much more efficient than R. As shown by the following microbenchmark, `sumC()` is competitive with the built-in (and highly optimised) `sum()`, while `sumR()` is several orders of magnitude slower.
```{r sum-bench, cache = TRUE}
x <- runif(1e3)
microbenchmark(
sum(x),
sumC(x),
sumR(x)
)
```
### Vector input, vector output
<!-- FIXME: come up with better example. Also fix in two other places it occurs -->
Next we'll create a function that computes the Euclidean distance between a value and a vector of values:
```{r pdist-r}
pdistR <- function(x, ys) {
sqrt((x - ys) ^ 2)
}
```
It's not obvious that we want `x` to be a scalar from the function definition. We'd need to make that clear in the documentation. That's not a problem in the C++ version because we have to be explicit about types:
```{r pdist-cpp, cache = TRUE}
cppFunction('NumericVector pdistC(double x, NumericVector ys) {
int n = ys.size();
NumericVector out(n);
for(int i = 0; i < n; ++i) {
out[i] = sqrt(pow(ys[i] - x, 2.0));
}
return out;
}')
```
This function introduces only a few new concepts:
* We create a new numeric vector of length `n` with a constructor:
`NumericVector out(n)`. Another useful way of making a vector is to copy an
existing one: `NumericVector zs = clone(ys)`.
* C++ uses `pow()`, not `^`, for exponentiation.
Note that because the R version is fully vectorised, it's already going to be fast. On my computer, it takes around 8 ms with a 1 million element `y` vector. The C++ function is twice as fast, ~4 ms, but assuming it took you 10 minutes to write the C++ function, you'd need to run it ~150,000 times to make rewriting worthwhile. The reason why the C++ function is faster is subtle, and relates to memory management. The R version needs to create an intermediate vector the same length as y (`x - ys`), and allocating memory is an expensive operation. The C++ function avoids this overhead because it uses an intermediate scalar.
In the sugar section, you'll see how to rewrite this function to take advantage of Rcpp's vectorised operations so that the C++ code is almost as concise as R code.
### Matrix input, vector output
Each vector type has a matrix equivalent: `NumericMatrix`, `IntegerMatrix`, `CharacterMatrix`, and `LogicalMatrix`. Using them is straightforward. For example, we could create a function that reproduces `rowSums()`:
```{r rowsums-cpp, cache = TRUE}
cppFunction('NumericVector rowSumsC(NumericMatrix x) {
int nrow = x.nrow(), ncol = x.ncol();
NumericVector out(nrow);
for (int i = 0; i < nrow; i++) {
double total = 0;
for (int j = 0; j < ncol; j++) {
total += x(i, j);
}
out[i] = total;
}
return out;
}')
set.seed(1014)
x <- matrix(sample(100), 10)
rowSums(x)
rowSumsC(x)
```
The main differences:
* In C++, you subset a matrix with `()`, not `[]`.
* Use `.nrow()` and `.ncol()` _methods_ to get the dimensions of a matrix.
### Using sourceCpp {#sourceCpp}
So far, we've used inline C++ with `cppFunction()`. This makes presentation simpler, but for real problems, it's usually easier to use stand-alone C++ files and then source them into R using `sourceCpp()`. This lets you take advantage of text editor support for C++ files (e.g., syntax highlighting) as well as making it easier to identify the line numbers in compilation errors. \indexc{sourceCpp()}
Your stand-alone C++ file should have extension `.cpp`, and needs to start with:
```cpp
#include <Rcpp.h>
using namespace Rcpp;
```
And for each function that you want available within R, you need to prefix it with:
```cpp
// [[Rcpp::export]]
```
Note that the space is mandatory.
If you're familiar with roxygen2, you might wonder how this relates to `@export`. `Rcpp::export` controls whether a function is exported from C++ to R; `@export` controls whether a function is exported from a package and made available to the user.
You can embed R code in special C++ comment blocks. This is really convenient if you want to run some test code:
```cpp
/*** R
# This is R code
*/
```
The R code is run with `source(echo = TRUE)` so you don't need to explicitly print output.
To compile the C++ code, use `sourceCpp("path/to/file.cpp")`. This will create the matching R functions and add them to your current session. Note that these functions can not be saved in a `.Rdata` file and reloaded in a later session; they must be recreated each time you restart R. For example, running `sourceCpp()` on the following file implements mean in C++ and then compares it to the built-in `mean()`:
```{r, engine = "Rcpp", eval = FALSE}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double meanC(NumericVector x) {
int n = x.size();
double total = 0;
for(int i = 0; i < n; ++i) {
total += x[i];
}
return total / n;
}
/*** R
library(microbenchmark)
x <- runif(1e5)
microbenchmark(
mean(x),
meanC(x)
)
*/
```
NB: if you run this code yourself, you'll notice that `meanC()` is much faster than the built-in `mean()`. This is because it trades numerical accuracy for speed.
For the remainder of this chapter C++ code will be presented stand-alone rather than wrapped in a call to `cppFunction`. If you want to try compiling and/or modifying the examples you should paste them into a C++ source file that includes the elements described above.
### Exercises
With the basics of C++ in hand, it's now a great time to practice by reading and writing some simple C++ functions. For each of the following functions, read the code and figure out what the corresponding base R function is. You might not understand every part of the code yet, but you should be able to figure out the basics of what the function does.
```cpp
double f1(NumericVector x) {
int n = x.size();
double y = 0;
for(int i = 0; i < n; ++i) {
y += x[i] / n;
}
return y;
}
NumericVector f2(NumericVector x) {
int n = x.size();
NumericVector out(n);
out[0] = x[0];
for(int i = 1; i < n; ++i) {
out[i] = out[i - 1] + x[i];
}
return out;
}
bool f3(LogicalVector x) {
int n = x.size();
for(int i = 0; i < n; ++i) {
if (x[i]) return true;
}
return false;
}
int f4(Function pred, List x) {
int n = x.size();
for(int i = 0; i < n; ++i) {
LogicalVector res = pred(x[i]);
if (res[0]) return i + 1;
}
return 0;
}
NumericVector f5(NumericVector x, NumericVector y) {
int n = std::max(x.size(), y.size());
NumericVector x1 = rep_len(x, n);
NumericVector y1 = rep_len(y, n);
NumericVector out(n);
for (int i = 0; i < n; ++i) {
out[i] = std::min(x1[i], y1[i]);
}
return out;
}
```
To practice your function writing skills, convert the following functions into C++. For now, assume the inputs have no missing values.
1. `all()`
2. `cumprod()`, `cummin()`, `cummax()`.
3. `diff()`. Start by assuming lag 1, and then generalise for lag `n`.
4. `range`.
5. `var`. Read about the approaches you can take on
[wikipedia](http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance).
Whenever implementing a numerical algorithm, it's always good to check what
is already known about the problem.
## Attributes and other classes {#rcpp-classes}
You've already seen the basic vector classes (`IntegerVector`, `NumericVector`, `LogicalVector`, `CharacterVector`) and their scalar (`int`, `double`, `bool`, `String`) and matrix (`IntegerMatrix`, `NumericMatrix`, `LogicalMatrix`, `CharacterMatrix`) equivalents.
All R objects have attributes, which can be queried and modified with `.attr()`. Rcpp also provides `.names()` as an alias for the name attribute. The following code snippet illustrates these methods. Note the use of `::create()`, a _class_ method. This allows you to create an R vector from C++ scalar values: \index{attributes!in C++ } \index{names!in C++}
```{r attribs, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector attribs() {
NumericVector out = NumericVector::create(1, 2, 3);
out.names() = CharacterVector::create("a", "b", "c");
out.attr("my-attr") = "my-value";
out.attr("class") = "my-class";
return out;
}
```
For S4 objects, `.slot()` plays a similar role to `.attr()`.
### Lists and data frames
Rcpp also provides classes `List` and `DataFrame`, but they are more useful for output than input. This is because lists and data frames can contain arbitrary classes but C++ needs to know their classes in advance. If the list has known structure (e.g., it's an S3 object), you can extract the components and manually convert them to their C++ equivalents with `as()`. For example, the object created by `lm()`, the function that fits a linear model, is a list whose components are always of the same type. The following code illustrates how you might extract the mean percentage error (`mpe()`) of a linear model. This isn't a good example of when to use C++, because it's so easily implemented in R, but it shows how to work with an important S3 class. Note the use of `.inherits()` and the `stop()` to check that the object really is a linear model. \index{lists!in C++} \index{data frames!in C++}
<!-- FIXME: needs better motivation -->
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double mpe(List mod) {
if (!mod.inherits("lm")) stop("Input must be a linear model");
NumericVector resid = as<NumericVector>(mod["residuals"]);
NumericVector fitted = as<NumericVector>(mod["fitted.values"]);
int n = resid.size();
double err = 0;
for(int i = 0; i < n; ++i) {
err += resid[i] / (fitted[i] + resid[i]);
}
return err / n;
}
```
```{r}
mod <- lm(mpg ~ wt, data = mtcars)
mpe(mod)
```
### Functions {#functions-rcpp}
You can put R functions in an object of type `Function`. This makes calling an R function from C++ straightforward. We first define our C++ function: \index{functions!in C++}
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
RObject callWithOne(Function f) {
return f(1);
}
```
Then call it from R:
```{r}
callWithOne(function(x) x + 1)
callWithOne(paste)
```
What type of object does an R function return? We don't know, so we use the catchall type `RObject`. An alternative is to return a `List`. For example, the following code is a basic implementation of `lapply` in C++:
```{r lapply1, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List lapply1(List input, Function f) {
int n = input.size();
List out(n);
for(int i = 0; i < n; i++) {
out[i] = f(input[i]);
}
return out;
}
```
Calling R functions with positional arguments is obvious:
```cpp
f("y", 1);
```
But to use named arguments, you need a special syntax:
```cpp
f(_["x"] = "y", _["value"] = 1);
```
### Other types
There are also classes for many more specialised language objects: `Environment`, `ComplexVector`, `RawVector`, `DottedPair`, `Language`, `Promise`, `Symbol`, `WeakReference`, and so on. These are beyond the scope of this chapter and won't be discussed further.
## Missing values {#rcpp-na}
If you're working with missing values, you need to know two things: \index{missing values!in C++}
* how R's missing values behave in C++'s scalars (e.g., `double`).
* how to get and set missing values in vectors (e.g., `NumericVector`).
### Scalars
The following code explores what happens when you take one of R's missing values, coerce it into a scalar, and then coerce back to an R vector. Note that this kind of experimentation is a useful way to figure out what any operation does.
```{r missings, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List scalar_missings() {
int int_s = NA_INTEGER;
String chr_s = NA_STRING;
bool lgl_s = NA_LOGICAL;
double num_s = NA_REAL;
return List::create(int_s, chr_s, lgl_s, num_s);
}
```
```{r}
str(scalar_missings())
```
With the exception of `bool`, things look pretty good here: all of the missing values have been preserved. However, as we'll see in the following sections, things are not quite as straightforward as they seem.
#### Integers
With integers, missing values are stored as the smallest integer. If you don't do anything to them, they'll be preserved. But, since C++ doesn't know that the smallest integer has this special behaviour, if you do anything to it you're likely to get an incorrect value: for example, `evalCpp('NA_INTEGER + 1')` gives -2147483647.
So if you want to work with missing values in integers, either use a length one `IntegerVector` or be very careful with your code.
#### Doubles
With doubles, you may be able to get away with ignoring missing values and working with NaNs (not a number). This is because R's NA is a special type of IEEE 754 floating point number NaN. So any logical expression that involves a NaN (or in C++, NAN) always evaluates as FALSE:
```{r, echo = FALSE, message = FALSE}
library(Rcpp)
```
```{r}
evalCpp("NAN == 1")
evalCpp("NAN < 1")
evalCpp("NAN > 1")
evalCpp("NAN == NAN")
```
But be careful when combining them with boolean values:
```{r}
evalCpp("NAN && TRUE")
evalCpp("NAN || FALSE")
```
However, in numeric contexts NaNs will propagate NAs:
```{r}
evalCpp("NAN + 1")
evalCpp("NAN - 1")
evalCpp("NAN / 1")
evalCpp("NAN * 1")
```
### Strings
`String` is a scalar string class introduced by Rcpp, so it knows how to deal with missing values.
### Boolean
While C++'s `bool` has two possible values (`true` or `false`), a logical vector in R has three (`TRUE`, `FALSE`, and `NA`). If you coerce a length 1 logical vector, make sure it doesn't contain any missing values otherwise they will be converted to TRUE.
### Vectors {#vectors-rcpp}
With vectors, you need to use a missing value specific to the type of vector, `NA_REAL`, `NA_INTEGER`, `NA_LOGICAL`, `NA_STRING`:
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List missing_sampler() {
return List::create(
NumericVector::create(NA_REAL),
IntegerVector::create(NA_INTEGER),
LogicalVector::create(NA_LOGICAL),
CharacterVector::create(NA_STRING));
}
```
```{r}
str(missing_sampler())
```
To check if a value in a vector is missing, use the class method `::is_na()`:
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
LogicalVector is_naC(NumericVector x) {
int n = x.size();
LogicalVector out(n);
for (int i = 0; i < n; ++i) {
out[i] = NumericVector::is_na(x[i]);
}
return out;
}
```
```{r}
is_naC(c(NA, 5.4, 3.2, NA))
```
Another alternative is the sugar function `is_na()`, which takes a vector and returns a logical vector.
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
LogicalVector is_naC2(NumericVector x) {
return is_na(x);
}
```
```{r}
is_naC2(c(NA, 5.4, 3.2, NA))
```
### Exercises
1. Rewrite any of the functions from the first exercise to deal with missing
values. If `na.rm` is true, ignore the missing values. If `na.rm` is false,
return a missing value if the input contains any missing values. Some
good functions to practice with are `min()`, `max()`, `range()`, `mean()`,
and `var()`.
1. Rewrite `cumsum()` and `diff()` so they can handle missing values. Note that
these functions have slightly more complicated behaviour.
## Rcpp sugar {#rcpp-sugar}
Rcpp provides a lot of syntactic "sugar" to ensure that C++ functions work very similarly to their R equivalents. In fact, Rcpp sugar makes it possible to write efficient C++ code that looks almost identical to its R equivalent. If there's a sugar version of the function you're interested in, you should use it: it'll be both expressive and well tested. Sugar functions aren't always faster than a handwritten equivalent, but they will get faster in the future as more time is spent on optimising Rcpp.
Sugar functions can be roughly broken down into
* arithmetic and logical operators
* logical summary functions
* vector views
* other useful functions
### Arithmetic and logical operators
All the basic arithmetic and logical operators are vectorised: `+`, `*`, `-`, `/`, `pow`, `<`, `<=`, `>`, `>=`, `==`, `!=`, `!`. For example, we could use sugar to considerably simplify the implementation of `pdistC()`.
```{r}
pdistR <- function(x, ys) {
sqrt((x - ys) ^ 2)
}
```
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector pdistC2(double x, NumericVector ys) {
return sqrt(pow((x - ys), 2));
}
```
### Logical summary functions
The sugar function `any()` and `all()` are fully lazy so that `any(x == 0)`, for example, might only need to evaluate one element of a vector, and return a special type that can be converted into a `bool` using `.is_true()`, `.is_false()`, or `.is_na()`. We could also use this sugar to write an efficient function to determine whether or not a numeric vector contains any missing values. To do this in R, we could use `any(is.na(x))`:
```{r}
any_naR <- function(x) any(is.na(x))
```
However, this will do the same amount of work regardless of the location of the missing value. Here's the C++ implementation:
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
bool any_naC(NumericVector x) {
return is_true(any(is_na(x)));
}
```
```{r, cache = TRUE}
x0 <- runif(1e5)
x1 <- c(x0, NA)
x2 <- c(NA, x0)
microbenchmark(
any_naR(x0), any_naC(x0),
any_naR(x1), any_naC(x1),
any_naR(x2), any_naC(x2)
)
```
### Vector views
A number of helpful functions provide a "view" of a vector: `head()`, `tail()`, `rep_each()`, `rep_len()`, `rev()`, `seq_along()`, and `seq_len()`. In R these would all produce copies of the vector, but in Rcpp they simply point to the existing vector and override the subsetting operator (`[`) to implement special behaviour. This makes them very efficient: for instance, `rep_len(x, 1e6)` does not have to make a million copies of x.
### Other useful functions
Finally, there's a grab bag of sugar functions that mimic frequently used R functions:
* Math functions: `abs()`, `acos()`, `asin()`, `atan()`, `beta()`, `ceil()`,
`ceiling()`, `choose()`, `cos()`, `cosh()`, `digamma()`, `exp()`, `expm1()`,
`factorial()`, `floor()`, `gamma()`, `lbeta()`, `lchoose()`, `lfactorial()`,
`lgamma()`, `log()`, `log10()`, `log1p()`, `pentagamma()`, `psigamma()`,
`round()`, `signif()`, `sin()`, `sinh()`, `sqrt()`, `tan()`, `tanh()`,
`tetragamma()`, `trigamma()`, `trunc()`.
* Scalar summaries: `mean()`, `min()`, `max()`, `sum()`, `sd()`, and
(for vectors) `var()`.
* Vector summaries: `cumsum()`, `diff()`, `pmin()`, and `pmax()`.
* Finding values: `match()`, `self_match()`, `which_max()`, `which_min()`.
* Dealing with duplicates: `duplicated()`, `unique()`.
* `d/q/p/r` for all standard distributions.
Finally, `noNA(x)` asserts that the vector `x` does not contain any missing values, and allows optimisation of some mathematical operations. For example, when computing the mean of a vector with no missing values, Rcpp doesn't need to check each value is not missing when computing the sum and the length.
## The STL {#stl}
The real strength of C++ shows itself when you need to implement more complex algorithms. The standard template library (STL) provides a set of extremely useful data structures and algorithms. This section will explain some of the most important algorithms and data structures and point you in the right direction to learn more. I can't teach you everything you need to know about the STL, but hopefully the examples will show you the power of the STL, and persuade you that it's useful to learn more. \index{standard template library}
If you need an algorithm or data structure that isn't implemented in STL, a good place to look is [boost](http://www.boost.org/doc/). Installing boost on your computer is beyond the scope of this chapter, but once you have it installed, you can use boost data structures and algorithms by including the appropriate header file with (e.g.) `#include <boost/array.hpp>`.
### Using iterators
Iterators are used extensively in the STL: many functions either accept or return iterators. They are the next step up from basic loops, abstracting away the details of the underlying data structure. Iterators have three main operators: \index{iterators}
1. Advance with `++`.
1. Get the value they refer to, or __dereference__, with `*`.
1. Compare with `==`.
For example we could re-write our sum function using iterators:
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sum3(NumericVector x) {
double total = 0;
NumericVector::iterator it;
for(it = x.begin(); it != x.end(); ++it) {
total += *it;
}
return total;
}
```
The main changes are in the for loop:
* We start at `x.begin()` and loop until we get to `x.end()`. A small
optimization is to store the value of the end iterator so we don't need to
look it up each time. This only saves about 2 ns per iteration, so it's only
important when the calculations in the loop are very simple.
* Instead of indexing into x, we use the dereference operator to get its
current value: `*it`.
* Notice the type of the iterator: `NumericVector::iterator`. Each vector
type has its own iterator type: `LogicalVector::iterator`,
`CharacterVector::iterator`, etc.
Iterators also allow us to use the C++ equivalents of the apply family of functions. For example, we could again rewrite `sum()` to use the `accumulate()` function, which takes a starting and an ending iterator, and adds up all the values in the vector. The third argument to accumulate gives the initial value: it's particularly important because this also determines the data type that accumulate uses (so we use `0.0` and not `0` so that accumulate uses a `double`, not an `int`.). To use `accumulate()` we need to include the `<numeric>` header.
```{r, engine = "Rcpp"}
#include <numeric>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
double sum4(NumericVector x) {
return std::accumulate(x.begin(), x.end(), 0.0);
}
```
`accumulate()` (along with the other functions in `<numeric>`, like `adjacent_difference()`, `inner_product()`, and `partial_sum()`) is not that important in Rcpp because Rcpp sugar provides equivalents.
### Algorithms
The `<algorithm>` header provides a large number of algorithms that work with iterators. A good reference is available at <http://www.cplusplus.com/reference/algorithm/>. For example, we could write a basic Rcpp version of `findInterval()` that takes two arguments a vector of values and a vector of breaks, and locates the bin that each x falls into. This shows off a few more advanced iterator features. Read the code below and see if you can figure out how it works. \indexc{findInterval()}
```{r, engine = "Rcpp"}
#include <algorithm>
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector findInterval2(NumericVector x, NumericVector breaks) {
IntegerVector out(x.size());
NumericVector::iterator it, pos;
IntegerVector::iterator out_it;
for(it = x.begin(), out_it = out.begin(); it != x.end();
++it, ++out_it) {
pos = std::upper_bound(breaks.begin(), breaks.end(), *it);
*out_it = std::distance(breaks.begin(), pos);
}
return out;
}
```
The key points are:
* We step through two iterators (input and output) simultaneously.
* We can assign into an dereferenced iterator (`out_it`) to change the values
in `out`.
* `upper_bound()` returns an iterator. If we wanted the value of the
`upper_bound()` we could dereference it; to figure out its location, we
use the `distance()` function.
* Small note: if we want this function to be as fast as `findInterval()` in R
(which uses handwritten C code), we need to compute the calls to `.begin()`
and `.end()` once and save the results. This is easy, but it distracts from
this example so it has been omitted. Making this change yields a function
that's slightly faster than R's `findInterval()` function, but is about 1/10
of the code.
It's generally better to use algorithms from the STL than hand rolled loops. In _Effective STL_, Scott Meyers gives three reasons: efficiency, correctness, and maintainability. Algorithms from the STL are written by C++ experts to be extremely efficient, and they have been around for a long time so they are well tested. Using standard algorithms also makes the intent of your code more clear, helping to make it more readable and more maintainable.
### Data structures {#data-structures-rcpp}
The STL provides a large set of data structures: `array`, `bitset`, `list`, `forward_list`, `map`, `multimap`, `multiset`, `priority_queue`, `queue`, `deque`, `set`, `stack`, `unordered_map`, `unordered_set`, `unordered_multimap`, `unordered_multiset`, and `vector`. The most important of these data structures are the `vector`, the `unordered_set`, and the `unordered_map`. We'll focus on these three in this section, but using the others is similar: they just have different performance trade-offs. For example, the `deque` (pronounced "deck") has a very similar interface to vectors but a different underlying implementation that has different performance trade-offs. You may want to try them for your problem. A good reference for STL data structures is <http://www.cplusplus.com/reference/stl/> --- I recommend you keep it open while working with the STL.
Rcpp knows how to convert from many STL data structures to their R equivalents, so you can return them from your functions without explicitly converting to R data structures.
### Vectors {#vectors-stl}
An STL vector is very similar to an R vector, except that it grows efficiently. This makes vectors appropriate to use when you don't know in advance how big the output will be. Vectors are templated, which means that you need to specify the type of object the vector will contain when you create it: `vector<int>`, `vector<bool>`, `vector<double>`, `vector<String>`. You can access individual elements of a vector using the standard `[]` notation, and you can add a new element to the end of the vector using `.push_back()`. If you have some idea in advance how big the vector will be, you can use `.reserve()` to allocate sufficient storage. \index{vectors!in C++}
The following code implements run length encoding (`rle()`). It produces two vectors of output: a vector of values, and a vector `lengths` giving how many times each element is repeated. It works by looping through the input vector `x` comparing each value to the previous: if it's the same, then it increments the last value in `lengths`; if it's different, it adds the value to the end of `values`, and sets the corresponding length to 1.
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List rleC(NumericVector x) {
std::vector<int> lengths;
std::vector<double> values;
// Initialise first value
int i = 0;
double prev = x[0];
values.push_back(prev);
lengths.push_back(1);
NumericVector::iterator it;
for(it = x.begin() + 1; it != x.end(); ++it) {
if (prev == *it) {
lengths[i]++;
} else {
values.push_back(*it);
lengths.push_back(1);
i++;
prev = *it;
}
}
return List::create(
_["lengths"] = lengths,
_["values"] = values
);
}
```
(An alternative implementation would be to replace `i` with the iterator `lengths.rbegin()` which always points to the last element of the vector. You might want to try implementing that yourself.)
Other methods of a vector are described at <http://www.cplusplus.com/reference/vector/vector/>.
### Sets
Sets maintain a unique set of values, and can efficiently tell if you've seen a value before. They are useful for problems that involve duplicates or unique values (like `unique`, `duplicated`, or `in`). C++ provides both ordered (`std::set`) and unordered sets (`std::unordered_set`), depending on whether or not order matters for you. Unordered sets tend to be much faster (because they use a hash table internally rather than a tree), so even if you need an ordered set, you should consider using an unordered set and then sorting the output. Like vectors, sets are templated, so you need to request the appropriate type of set for your purpose: `unordered_set<int>`, `unordered_set<bool>`, etc. More details are available at <http://www.cplusplus.com/reference/set/set/> and <http://www.cplusplus.com/reference/unordered_set/unordered_set/>. \index{sets}
The following function uses an unordered set to implement an equivalent to `duplicated()` for integer vectors. Note the use of `seen.insert(x[i]).second`. `insert()` returns a pair, the `.first` value is an iterator that points to element and the `.second` value is a boolean that's true if the value was a new addition to the set.
```{r, engine = "Rcpp"}
// [[Rcpp::plugins(cpp11)]]
#include <Rcpp.h>
#include <unordered_set>
using namespace Rcpp;
// [[Rcpp::export]]
LogicalVector duplicatedC(IntegerVector x) {
std::unordered_set<int> seen;
int n = x.size();
LogicalVector out(n);
for (int i = 0; i < n; ++i) {
out[i] = !seen.insert(x[i]).second;
}
return out;
}
```
Note that unordered sets are only available in C++ 11, which means we need to use the `cpp11` plugin, `[[Rcpp::plugins(cpp11)]]`.
### Map
A map is similar to a set, but instead of storing presence or absence, it can store additional data. It's useful for functions like `table()` or `match()` that need to look up a value. As with sets, there are ordered (`std::map`) and unordered (`std::unordered_map`) versions. Since maps have a value and a key, you need to specify both types when initialising a map: `map<double, int>`, `unordered_map<int, double>`, and so on. The following example shows how you could use a `map` to implement `table()` for numeric vectors: \index{maps}
```{r, engine = "Rcpp"}
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
std::map<double, int> tableC(NumericVector x) {
std::map<double, int> counts;
int n = x.size();
for (int i = 0; i < n; i++) {
counts[x[i]]++;
}
return counts;
}
```
Note that unordered maps are only available in C++ 11, so to use them, you'll again need `[[Rcpp::plugins(cpp11)]]`.
### Exercises