Viết hàm trong C++

Tối ưu hóa mã R với Rcpp

Romain François

Consulting Datactive, ThinkR

Chỉ đừng export hàm nội bộ

#include <Rcpp.h>
using namespace Rcpp ;

int twice( int x ){
  return 2*x ;
}

// [[Rcpp::export]]
int universal(){
  return twice(21) ;
}
Tối ưu hóa mã R với Rcpp

Chỉ đừng export hàm nội bộ

Gọi từ R:

# Không thể, twice là hàm nội bộ
twice(21)
Error in twice(21) : could not find function "twice"
# Ổn
universal()
42
Tối ưu hóa mã R với Rcpp

Chú thích trong C++

Chú thích đến hết dòng:

// A comment

Chú thích nhiều dòng

/*
   A longer comment 
   that takes multiple lines

   sometimes used to quarantine a piece of code, 
   for example

   int x = 42 ;
*/
int x = 38 ;
Tối ưu hóa mã R với Rcpp

Chú thích đặc biệt cho mã R

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

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

/*** R
  # Đây là mã R
  12 + 30

  # Gọi hàm `universal`
  universal()
*/
Tối ưu hóa mã R với Rcpp

if và else

if( condition ){
  // code if true
} else {
  // code otherwise
}
Tối ưu hóa mã R với Rcpp
// [[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
Tối ưu hóa mã R với Rcpp

Cùng luyện tập nào!

Tối ưu hóa mã R với Rcpp

Preparing Video For Download...