Laços while

Otimizando código R com Rcpp

Romain François

Consulting Datactive, ThinkR

Laços while são mais simples

while( condition ){
    body
}
  • Condição de continuação
  • Corpo do laço
Otimizando código R com 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 ;
}

Depois de compilar a função com sourceCpp, você pode chamá-la:

power( 1000 )
power( 17 )
1024
32
Otimizando código R com Rcpp

Laços for são apenas while

for( init ; condition; increment ){
    body
}

où equivalente a

init
while( condition ){
    body
    increment
}
Otimizando código R com Rcpp

Laços do/while

do {
    body
} while( condition ) ;
Otimizando código R com Rcpp

Exemplo de laço do/while

// [[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 ;
}
Otimizando código R com Rcpp

Vamos praticar!

Otimizando código R com Rcpp

Preparing Video For Download...