Depuração

Otimizando código R com Rcpp

Romain François

Consulting Datactive, ThinkR

Imprimir no console

Uma função que usa Rprintf() para imprimir uma mensagem no console

cppFunction( '
int fun(){  

    // Some values
    int x = 42 ;

    // Printing a message to the R console
    Rprintf( "some message in the console, x=%d\\n", x ) ;

    // Return some int
    return 76 ;
}
')
Otimizando código R com Rcpp

Rprintf e placeholders

Placeholder de inteiro com %d

int x = 42 ;

Rprintf( "some message in the console, x=%d\n", x ) ;

// Prints the following in the console: 
some message in the console, x=42

Placeholder de string com %s

Rprintf( "roses are %s, violets are %s\n", "red", "blue" ) ;

// Prints the following:
roses are red, violets are blue
Otimizando código R com Rcpp

Uma função que usa Rprintf() para imprimir uma mensagem no console

cppFunction( 'int fun(){  
    // some values
    int x = 42 ;

    // printing a message to the R console
    Rprintf( "some message in the console, x=%d\\n", x ) ;

    // return some int
    return 76 ;}     ')

Chamando a função

fun()
some message in the console, x=42
76
Otimizando código R com Rcpp

Mensagens de erro

Uma função que só aceita números entre 0 e 20

cppFunction( 'int fun(int x){  
    // A simple error message
    if( x < 0 ) stop( "sorry x should be positive" ) ;    
    // A formatted error message 
    if( x > 20 ) stop( "x is too big (x=%d)", x ) ;    
    // Return some int
    return x ;     }')
fun(-2)
Error in fun(-2) : sorry x should be positive
Otimizando código R com Rcpp

Mensagens de erro

fun(23)
Error in fun(23) : x is too big (x=23)
tryCatch( fun(24), error = function(e){
    message("C++ exception caught: ", conditionMessage(e))
})
C++ exception caught: x is too big (x=24)
Otimizando código R com Rcpp

Vamos praticar!

Otimizando código R com Rcpp

Preparing Video For Download...