C++ functions belong to C++ files

Ottimizzare il codice R con Rcpp

Romain François

Consulting Datactive, ThinkR

Previously, in this course

evalCpp()

evalCpp( "40 + 2" )
42

cppFunction()

cppFunction( "int fun(){ return 42; }")
fun()
42
Ottimizzare il codice R con 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
Ottimizzare il codice R con Rcpp

Include the Rcpp header file

#include <Rcpp.h>
_____ _________ ____ _

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

    • It includes all other header files automatically
Ottimizzare il codice R con Rcpp

Using the Rcpp namespace

#include <Rcpp.h>
using namespace Rcpp ;

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Use Something instead of Rcpp::Something, when Something is in Rcpp
Ottimizzare il codice R con Rcpp

Exporting the function to R

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
___ _________ ___ _ __
  ______ ___ _
_
Ottimizzare il codice R con Rcpp

The function itself

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int timesTwo( int x ){
  return 2*x ;
}
Ottimizzare il codice R con 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
Ottimizzare il codice R con Rcpp

Let's practice!

Ottimizzare il codice R con Rcpp

Preparing Video For Download...