用 Rcpp 最佳化 R 程式碼
Romain François
Consulting Datactive, ThinkR
evalCpp()
evalCpp( "40 + 2" )
42
cppFunction()
cppFunction( "int fun(){ return 42; }")
fun()
42
在 code.cpp 中的 C++ 程式碼
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int timesTwo( int x ){
return 2*x ;
}
使用 sourceCpp() 編譯並載入
library(Rcpp)
sourceCpp( "code.cpp" )
timesTwo( 21 )
42
#include <Rcpp.h>
_____ _________ ____ _
__ ________________
___ _________ ___ _ __
______ ___ _
_
只需引入 Rcpp.h
#include <Rcpp.h>
using namespace Rcpp ;
__ ________________
___ _________ ___ _ __
______ ___ _
_
Something 位於 Rcpp 中時,可用 Something 取代 Rcpp::Something#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
___ _________ ___ _ __
______ ___ _
_
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int timesTwo( int x ){
return 2*x ;
}
#include <Rcpp.h>
using namespace Rcpp ;
// [[Rcpp::export]]
int timesTwo( int x ){
return 2*x ;}
將函式載入 R
library(Rcpp)
sourceCpp( "code.cpp" )
像一般 R 函式一樣呼叫。
timesTwo( 21 )
42
用 Rcpp 最佳化 R 程式碼