Optimizing R Code with Rcpp
Romain François
Consulting Datactive, ThinkR
while( condition ){
body
}
// [[Rcpp::export]]
int power( int n ){
if( n < 0 ){
stop( "n must be positive" ) ;
}
int value = 1 ;
while( value < n ){
value = value * 2 ;
}
return value ;
}
Once the function is compiled with sourceCpp
, you can call it:
power( 1000 )
power( 17 )
1024
32
for( init ; condition; increment ){
body
}
is equivalent to
init
while( condition ){
body
increment
}
do {
body
} while( condition ) ;
// [[Rcpp::export]]
int power( int n ){
if( n < 0 ){
stop( "n must be positive" ) ;
}
int value = 1 ;
do {
value = value * 2 ;
} while( value < n );
return value ;
}
Optimizing R Code with Rcpp