Writing functions in C++

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Just don't export internal functions

#include <Rcpp.h>
using namespace Rcpp ;

int twice( int x ){
  return 2*x ;
}

// [[Rcpp::export]]
int universal(){
  return twice(21) ;
}
Optimizing R Code with Rcpp

Just don't export internal functions

Calling from R:

# Not possible, twice is internal
twice(21)
Error in twice(21) : could not find function "twice"
# Fine
universal()
42
Optimizing R Code with Rcpp

C++ comments

Comment until the end of the line:

// A comment

Comments spanning multiple lines

/*
   A longer comment 
   that takes multiple lines

   sometimes used to quarantine a piece of code, 
   for example

   int x = 42 ;
*/
int x = 38 ;
Optimizing R Code with Rcpp

R code special comment

#include <Rcpp.h>
using namespace Rcpp ;
int twice( int x ){
  return 2*x ;}

// [[Rcpp::export]]
int universal(){
  return twice(21) ;}

/*** R
  # This is R code
  12 + 30

  # Calling the `universal` function
  universal()
*/
Optimizing R Code with Rcpp

if and else

if( condition ){
  // code if true
} else {
  // code otherwise
}
Optimizing R Code with Rcpp
// [[Rcpp::export]]
void info( double x){
    if( x < 0 ){
        Rprintf( "x is negative" ) ;  
    } else if( x == 0 ){
        Rprintf( "x is zero" ) ;
    } else if( x > 0 ){
        Rprintf( "x is positive" ) ;
    } else {
        Rprintf( "x is not a number" ) ;
    }
}
info(-2)                        info(0)
x is negative                   x is zero
info(3)                         info(NaN)
x is positive                   x is not a number
Optimizing R Code with Rcpp

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...