调试

用 Rcpp 优化 R 代码

Romain François

Consulting Datactive, ThinkR

打印到控制台

使用 Rprintf() 向控制台打印消息的函数

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 ;
}
')
用 Rcpp 优化 R 代码

Rprintf 与占位符

整数占位符 %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

字符串占位符 %s

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

// Prints the following:
roses are red, violets are blue
用 Rcpp 优化 R 代码

使用 Rprintf() 向控制台打印消息的函数

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 ;}     ')

调用函数

fun()
some message in the console, x=42
76
用 Rcpp 优化 R 代码

错误信息

仅接受 0 到 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
用 Rcpp 优化 R 代码

错误信息

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)
用 Rcpp 优化 R 代码

让我们练习!

用 Rcpp 优化 R 代码

Preparing Video For Download...