恭喜!

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