Rcpp ile R Kodunu Optimize Etme
Romain François
Consulting Datactive, ThinkR
Konsola mesaj yazdırmak için Rprintf() kullanan bir fonksiyon
cppFunction( '
int fun(){
// Bazı değerler
int x = 42 ;
// R konsoluna mesaj yazdırma
Rprintf( "some message in the console, x=%d\\n", x ) ;
// Bir int döndür
return 76 ;
}
')
%d ile tamsayı yer tutucu
int x = 42 ;
Rprintf( "some message in the console, x=%d\n", x ) ;
// Konsolda şunu yazdırır:
some message in the console, x=42
%s ile metin yer tutucu
Rprintf( "roses are %s, violets are %s\n", "red", "blue" ) ;
// Şunu yazdırır:
roses are red, violets are blue
Konsola mesaj yazdırmak için Rprintf() kullanan bir fonksiyon
cppFunction( 'int fun(){
// bazı değerler
int x = 42 ;
// R konsoluna mesaj yazdırma
Rprintf( "some message in the console, x=%d\\n", x ) ;
// bir int döndür
return 76 ;} ')
Fonksiyonu çağırma
fun()
some message in the console, x=42
76
Yalnızca 0 ile 20 arasındaki sayıları alan bir fonksiyon
cppFunction( 'int fun(int x){
// Basit bir hata mesajı
if( x < 0 ) stop( "sorry x should be positive" ) ;
// Biçimlendirilmiş bir hata mesajı
if( x > 20 ) stop( "x is too big (x=%d)", x ) ;
// Bir int döndür
return x ; }')
fun(-2)
Error in fun(-2) : sorry x should be positive
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 ile R Kodunu Optimize Etme