Aan de slagGa gratis aan de slag

if and if/else

Just like in R, you can use the if and else keywords for branching. The syntax is the same as in R.

if(condition) {
  // Code to run if the condition is TRUE
} else {
  // Code to run otherwise
}

Here you'll use if and else to complete the definition of an absolute() function to calculate the absolute value of a floating point number. (This mimics the C++ function fabs().)

Deze oefening maakt deel uit van de cursus

Optimizing R Code with Rcpp

Cursus bekijken

Oefeninstructies

  • Test if x is greater than zero.
  • If the condition holds, return x.
  • Add the keyword for what to do otherwise.
  • If the condition doesn't hold, return negative x.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

#include 
using namespace Rcpp ;

// [[Rcpp::export]]
double absolute(double x) {
  // Test for x greater than zero
  ___(___) {
    // Return x
    ___;
  // Otherwise
  } ___ {
    // Return negative x
    ___;
  }
}

/*** R  
absolute(pi)
absolute(-3)
*/
Code bewerken en uitvoeren