用 Rcpp 优化 R 代码
Romain François
Consulting Datactive, ThinkR
#include <Rcpp.h>
using namespace Rcpp ;
int twice( int x ){
return 2*x ;
}
// [[Rcpp::export]]
int universal(){
return twice(21) ;
}
从 R 调用:
# 不可行,twice 是内部函数
twice(21)
Error in twice(21) : could not find function "twice"
# 可以
universal()
42
行尾注释:
// 一条注释
多行注释:
/*
更长的注释,
跨多行
有时用于隔离一段代码,
例如:
int x = 42 ;
*/
int x = 38 ;
#include <Rcpp.h>
using namespace Rcpp ;
int twice( int x ){
return 2*x ;}
// [[Rcpp::export]]
int universal(){
return twice(21) ;}
/*** R
# 这是 R 代码
12 + 30
# 调用 `universal` 函数
universal()
*/
if( condition ){
// 条件为真时执行
} else {
// 否则执行
}
// [[Rcpp::export]]
void info( double x){
if( x < 0 ){
Rprintf( "x is negative" ) ;
} else if( x == 0 ){
Rprintf( "x is zero" ) ;
} else if( x > 0 ){
Rprintf( "x is positive" ) ;
} else {
Rprintf( "x is not a number" ) ;
}
}
info(-2) info(0)
x 为负数 x 为零
info(3) info(NaN)
x 为正数 x 不是数字
用 Rcpp 优化 R 代码