Funkce C++ patří do souborů C++

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

Dříve v tomto kurzu

evalCpp()

evalCpp( "40 + 2" )
42

cppFunction()

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

Kód C++ v souboru code.cpp

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

Funkce sourceCpp() kód zkompiluje a načte

library(Rcpp)

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

Vložení hlavičkového souboru Rcpp

#include <Rcpp.h>
_____ _________ ____ _

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Vložte pouze Rcpp.h

    • Automaticky zahrne všechny ostatní hlavičkové soubory
Optimizing R Code with Rcpp

Použití jmenného prostoru Rcpp

#include <Rcpp.h>
using namespace Rcpp ;

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Místo Rcpp::Something použijte Something, pokud je Something v Rcpp
Optimizing R Code with Rcpp

Export funkce do R

#include <Rcpp.h>
using namespace Rcpp ;

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

Samotná funkce

#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 ;}

Načtení funkce do R

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

Volání jako jakékoli jiné funkce R.

timesTwo( 21 )
42
Optimizing R Code with Rcpp

Lass uns üben!

Optimizing R Code with Rcpp

Preparing Video For Download...