おめでとうございます!

Rcpp で R コードを最適化する

Romain François

Consulting Datactive, ThinkR

evalCpp と cppFunction

  • 簡単な C++ 式の評価
evalCpp( "40+2" )
42
  • R コンソールから C++ 関数を作成する
cppFunction( "double add( double x, double y){
    return x + y ;
}")
add( 40, 2 )
42
Rcpp で R コードを最適化する

for ループ

for( init ; condition ; increment ){
    body
}
  • init: 最初に実行される処理
  • condition: ループを継続するか
  • increment: 各反復後の処理
  • body: ループ本体の処理
Rcpp で R コードを最適化する

for ループ

for( int i=0; i<n; i++){
    // do something with i
}
Rcpp で R コードを最適化する

ベクトルのインデックス参照

NumericVector x = ... ; 
int n = x.size() ;
// first value
x[0]
// second value
x[1]
// last value
x[n-1]
Rcpp で R コードを最適化する

Rcpp を使った C++ ファイル

#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;
}
Rcpp で R コードを最適化する

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 ;
}
Rcpp で R コードを最適化する

おめでとうございます!

Rcpp で R コードを最適化する

Preparing Video For Download...