Gratulujeme!

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

evalCpp a cppFunction

  • Vyhodnocení jednoduchých příkazů C++
evalCpp( "40+2" )
42
  • Vytvoření funkce C++ z konzole R
cppFunction( "double add( double x, double y){
    return x + y ;
}")
add( 40, 2 )
42
Optimizing R Code with Rcpp

Smyčky for

for( init ; condition ; increment ){
    body
}
  • init: co se provede na začátku
  • condition: zda má smyčka pokračovat
  • increment: po každé iteraci
  • body: co smyčka vykonává
Optimizing R Code with Rcpp

Smyčky for

for( int i=0; i<n; i++){
    // do something with i
}
Optimizing R Code with Rcpp

Indexování vektorů

NumericVector x = ... ; 
int n = x.size() ;
// first value
x[0]
// second value
x[1]
// last value
x[n-1]
Optimizing R Code with Rcpp

Soubory C++ s Rcpp

#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
double add( double x, double y){
    return x + y ;
}
// [[Rcpp::export]]
double twice( double x){
    return 2.0 * x;
}
Optimizing R Code with Rcpp

Typická funkce Rcpp

#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
double fun( NumericVector x ){

    // extract data from input and prepare outputs
    int n = x.size() ;
    double res = 0.0 ;

    // loop around input and/or output
    for(int i=0; i<n; i++){
        // do something with x[i]
    }

    // return output
    return res ;
}
Optimizing R Code with Rcpp

Gratulujeme!

Optimizing R Code with Rcpp

Preparing Video For Download...