C++'ta fonksiyon yazma

Rcpp ile R Kodunu Optimize Etme

Romain François

Consulting Datactive, ThinkR

İç fonksiyonları dışa aktarma

#include <Rcpp.h>
using namespace Rcpp ;

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

// [[Rcpp::export]]
int universal(){
  return twice(21) ;
}
Rcpp ile R Kodunu Optimize Etme

İç fonksiyonları dışa aktarma

R'den çağırma:

# Olmaz, twice içsel
twice(21)
Error in twice(21) : could not find function "twice"
# Sorun yok
universal()
42
Rcpp ile R Kodunu Optimize Etme

C++ yorumları

Satır sonuna kadar yorum:

// Bir yorum

Birden çok satıra yayılan yorumlar

/*
   Birden uzun yorum 
   birden çok satır sürer

   bazen bir kod parçasını karantinaya almak için kullanılır, 
   örneğin

   int x = 42 ;
*/
int x = 38 ;
Rcpp ile R Kodunu Optimize Etme

R kodu özel yorumu

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

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

/*** R
  # Bu R kodu
  12 + 30

  # `universal` fonksiyonunu çağırma
  universal()
*/
Rcpp ile R Kodunu Optimize Etme

if ve else

if( condition ){
  // koşul doğruysa kod
} else {
  // değilse kod
}
Rcpp ile R Kodunu Optimize Etme
// [[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 ile R Kodunu Optimize Etme

Hadi pratik yapalım!

Rcpp ile R Kodunu Optimize Etme

Preparing Video For Download...