恭喜你!

用 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...