C++ 函数属于 C++ 文件

用 Rcpp 优化 R 代码

Romain François

Consulting Datactive, ThinkR

本课程前面内容

evalCpp()

evalCpp( "40 + 2" )
42

cppFunction()

cppFunction( "int fun(){ return 42; }")
fun()
42
用 Rcpp 优化 R 代码

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
用 Rcpp 优化 R 代码

包含 Rcpp 头文件

#include <Rcpp.h>
_____ _________ ____ _

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • 只包含 Rcpp.h

    • 它会自动包含其他头文件
用 Rcpp 优化 R 代码

使用 Rcpp 命名空间

#include <Rcpp.h>
using namespace Rcpp ;

__ ________________
___ _________ ___ _ __
  ______ ___ _
_
  • Something 属于 Rcpp 时,用 Something 代替 Rcpp::Something
用 Rcpp 优化 R 代码

将函数导出到 R

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
___ _________ ___ _ __
  ______ ___ _
_
用 Rcpp 优化 R 代码

函数本身

#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int timesTwo( int x ){
  return 2*x ;
}
用 Rcpp 优化 R 代码
#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 代码

Let's practice!

用 Rcpp 优化 R 代码

Preparing Video For Download...