25.2 Getting started with C++

library(Rcpp)

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: 0x7fe95ba7f4f0>, 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 and String
    • vector types (for Rcpp) are IntegerVector, NumericVector, LogicalVector and CharacterVector
    • Other R types are available in C++: List, Function, DataFrame, and more.
  • Explicitly use a return statement to return a value from a function.