For loops

Optimizing R Code with Rcpp

Romain François

Consulting Datactive, ThinkR

The 4 parts of C++ for loops

  • Initialization
  • Continue condition
  • Increment
  • Body
Optimizing R Code with Rcpp

For loops - the initialization

What happens at the very beginning of the loop:

for( init ;  ;  ){

}
Optimizing R Code with Rcpp

For loops - the continue condition

Logical condition to control if the loop continues

for(  ; condition ;  ){

}
Optimizing R Code with Rcpp

For loops - the increment

Executed at the end of each iteration

for(  ;  ; increment ){

}
Optimizing R Code with Rcpp

For loops - the body

Executed at each iteration. What the loop does.

for(  ;  ;  ){
    body
}
Optimizing R Code with Rcpp

Typical for loop

for (int i=0; i<n; i++ ){
    // some code using i
}
Optimizing R Code with Rcpp

Typical for loop

for (int i=0; ; ){

}
Optimizing R Code with Rcpp

Typical for loop

for (int i=0; i<n; ){

}
Optimizing R Code with Rcpp

Typical for loop

for (int i=0; i<n; i++){

}
Optimizing R Code with Rcpp

Example: sum of n first integers

// [[Rcpp::export]]
int nfirst( int n ){
    if( n < 0 ) {
        stop( "n must be positive, I see n=%d", n ) ;
    }

    int result = 0 ;
    for( int i=0; i<n; i++){
        result = result + (i+1) ;
    }

    return result ;
}
Optimizing R Code with Rcpp

Breaking out of a for loop

// [[Rcpp::export]]
int nfirst( int n ){
    if( n < 0 ) {
        stop( "n must be positive, I see n=%d", n ) ;
    }    

    int result = 0 ;
    for( int i=0; i<n; i++){
        if( i == 13 ){
            Rprintf( "I cannot handle that, I am superstitious" ) ;
            break ;
        }
        result = result + (i+1) ;
    }

    return result ;
}
Optimizing R Code with Rcpp

Newton iterative method to calculate square roots

Finding $\sqrt{S}$ is the same as finding the root of $f(x) = x^2 - S$

Leading to the iterative expression:

$$ x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)} = x_n - \frac{x^2_n - S}{2 x_n} = \frac{1}{2} \left( x_n + \frac{S}{x_n} \right) $$

Algorithm:

  • Take an initial value $x_0$
  • Update $x$ using the formula above a given number of times
Optimizing R Code with Rcpp

Newton's method in C++

$$ x_{n+1} = \frac{1}{2} \left( x_n + \frac{S}{x_n} \right) $$

translates to the pseudo code

int n = ... // number of iterations
double res = ... // initialization

for( int i=0; i<n; i++){
    // update the value of res
    // i.e. calculate x_{n+1} given x_{n}
    res = ( res + S / res ) / 2.0 ; 
}

return res ;
Optimizing R Code with Rcpp

Let's practice!

Optimizing R Code with Rcpp

Preparing Video For Download...