C++ functions belong to C++ files

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Previously, in this course

evalCpp()

evalCpp( "40 + 2" )
42

cppFunction()

cppFunction( "int fun(){ return 42; }")
fun()
42
Optimizing R Code with Rcpp

C++ code in code.cpp

#include <Rcpp.h>
using namespace Rcpp ; 
// [[Rcpp::export]]
int timesTwo( int x ){
  return 2*x ; 
}

The sourceCpp() function compiles and loads it

library(Rcpp)

sourceCpp( "code.cpp" )
timesTwo( 21 )
42
Optimizing R Code with Rcpp

Include the Rcpp header file

#include <Rcpp.h>
_____ _________ ____ _

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Include only Rcpp.h

    • It includes all other header files automatically
Optimizing R Code with Rcpp

Using the Rcpp namespace

#include <Rcpp.h>
using namespace Rcpp ;

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Use Something instead of Rcpp::Something, when Something is in Rcpp
Optimizing R Code with Rcpp

Exporting the function to R

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
___ _________ ___ _ __
  ______ ___ _
_
Optimizing R Code with Rcpp

The function itself

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int timesTwo( int x ){
  return 2*x ;
}
Optimizing R Code with Rcpp
#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int timesTwo( int x ){
  return 2*x ;}

load the function into R

library(Rcpp)
sourceCpp( "code.cpp" )

Call it, just as any other R function.

timesTwo( 21 )
42
Optimizing R Code with Rcpp

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...