C++ functions belong to C++ files

R-code optimaliseren met Rcpp

Romain François

Consulting Datactive, ThinkR

Previously, in this course

evalCpp()

evalCpp( "40 + 2" )
42

cppFunction()

cppFunction( "int fun(){ return 42; }")
fun()
42
R-code optimaliseren met 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
R-code optimaliseren met Rcpp

Include the Rcpp header file

#include <Rcpp.h>
_____ _________ ____ _

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

    • It includes all other header files automatically
R-code optimaliseren met Rcpp

Using the Rcpp namespace

#include <Rcpp.h>
using namespace Rcpp ;

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Use Something instead of Rcpp::Something, when Something is in Rcpp
R-code optimaliseren met Rcpp

Exporting the function to R

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
___ _________ ___ _ __
  ______ ___ _
_
R-code optimaliseren met Rcpp

The function itself

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int timesTwo( int x ){
  return 2*x ;
}
R-code optimaliseren met 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
R-code optimaliseren met Rcpp

Let's practice!

R-code optimaliseren met Rcpp

Preparing Video For Download...