Pisanie funkcji w C++

Optymalizacja kodu R za pomocą Rcpp

Romain François

Consulting Datactive, ThinkR

Nie eksportuj funkcji wewnętrznych

#include <Rcpp.h>
using namespace Rcpp ;

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

// [[Rcpp::export]]
int universal(){
  return twice(21) ;
}
Optymalizacja kodu R za pomocą Rcpp

Nie eksportuj funkcji wewnętrznych

Wywołanie z R:

# Niemożliwe – twice jest funkcją wewnętrzną
twice(21)
Error in twice(21) : could not find function "twice"
# Poprawne
universal()
42
Optymalizacja kodu R za pomocą Rcpp

Komentarze w C++

Komentarz do końca linii:

// A comment

Komentarze wieloliniowe

/*
   A longer comment 
   that takes multiple lines

   sometimes used to quarantine a piece of code, 
   for example

   int x = 42 ;
*/
int x = 38 ;
Optymalizacja kodu R za pomocą Rcpp

Specjalny komentarz z kodem 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()
*/
Optymalizacja kodu R za pomocą Rcpp

if i else

if( condition ){
  // code if true
} else {
  // code otherwise
}
Optymalizacja kodu R za pomocą 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
Optymalizacja kodu R za pomocą Rcpp

Czas na ćwiczenia!

Optymalizacja kodu R za pomocą Rcpp

Preparing Video For Download...