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...