While loops

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

While loops are simpler

while( condition ){
    body
}
  • Continue condition
  • Loop body
Optimizing R Code with Rcpp
// [[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
Optimizing R Code with Rcpp

For loops are just while loops

for( init ; condition; increment ){
    body
}

is equivalent to

init
while( condition ){
    body
    increment
}
Optimizing R Code with Rcpp

do / while loops

do {
    body
} while( condition ) ;
Optimizing R Code with Rcpp

Example of a do / while loop

// [[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

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...