Get startedGet started for free

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().)

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • 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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

#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)
*/
Edit and Run Code