用 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 代码