25.2 Getting started with C++
Install a C++ compiler:
- Rtools, on Windows
- Xcode, on Mac
- Sudo apt-get install r-base-dev or similar, on Linux.
First example
Rcpp compiling the C++ code:
cppFunction('int add(int x, int y, int z) {
int sum = x + y + z;
return sum;
}')
# add works like a regular R function
add
#> function (x, y, z)
#> .Call(<pointer: 0x7f8cc3c1e4f0>, x, y, z)
add(1, 2, 3)
#> [1] 6
Some things to note:
- The syntax to create a function is different.
- Types of inputs and outputs must be explicitly declared
- Use = for assignment, not
<-
. - Every statement is terminated by a ;
- C++ has it’s own name for the types we are used to:
- scalar types are
int
,double
,bool
andString
- vector types (for Rcpp) are
IntegerVector
,NumericVector
,LogicalVector
andCharacterVector
- Other R types are available in C++:
List
,Function
,DataFrame
, and more.
- scalar types are
- Explicitly use a
return
statement to return a value from a function.