在 C++ 撰寫函式

用 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) ;
}
用 Rcpp 最佳化 R 程式碼

不要匯出內部函式

從 R 呼叫:

# Not possible, twice is internal
twice(21)
Error in twice(21) : could not find function "twice"
# Fine
universal()
42
用 Rcpp 最佳化 R 程式碼

C++ 註解

行尾註解:

// A comment

跨多行的註解:

/*
   A longer comment 
   that takes multiple lines

   sometimes used to quarantine a piece of code, 
   for example

   int x = 42 ;
*/
int x = 38 ;
用 Rcpp 最佳化 R 程式碼

R 程式碼特別註解

#include <Rcpp.h>
using namespace Rcpp ;
int twice( int x ){
  return 2*x ;}

// [[Rcpp::export]]
int universal(){
  return twice(21) ;}

/*** R
  # This is R code
  12 + 30

  # Calling the `universal` function
  universal()
*/
用 Rcpp 最佳化 R 程式碼

if 與 else

if( condition ){
  // code if true
} else {
  // code otherwise
}
用 Rcpp 最佳化 R 程式碼
// [[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 is negative                   x is zero
info(3)                         info(NaN)
x is positive                   x is not a number
用 Rcpp 最佳化 R 程式碼

一起來練習吧!

用 Rcpp 最佳化 R 程式碼

Preparing Video For Download...