C++-funktioner hör till C++-filer

Optimera R-kod med Rcpp

Romain François

Consulting Datactive, ThinkR

Tidigare i kursen

evalCpp()

evalCpp( "40 + 2" )
42

cppFunction()

cppFunction( "int fun(){ return 42; }")
fun()
42
Optimera R-kod med Rcpp

C++-kod i code.cpp

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

Funktionen sourceCpp() kompilerar och läser in den

library(Rcpp)

sourceCpp( "code.cpp" )
timesTwo( 21 )
42
Optimera R-kod med Rcpp

Inkludera Rcpp-headerfilen

#include <Rcpp.h>
_____ _________ ____ _

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Inkludera bara Rcpp.h

    • Den inkluderar alla andra headerfiler automatiskt
Optimera R-kod med Rcpp

Använda Rcpp-namnrymden

#include <Rcpp.h>
using namespace Rcpp ;

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Använd Something i stället för Rcpp::Something, när Something finns i Rcpp
Optimera R-kod med Rcpp

Exportera funktionen till R

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
___ _________ ___ _ __
  ______ ___ _
_
Optimera R-kod med Rcpp

Själva funktionen

#include <Rcpp.h>
using namespace Rcpp ;

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

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

Läs in funktionen i R

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

Anropa den precis som vilken R-funktion som helst.

timesTwo( 21 )
42
Optimera R-kod med Rcpp

Nu kör vi en övning!

Optimera R-kod med Rcpp

Preparing Video For Download...