Get startedGet started for free

First function - again

Recall the the_answer() function from Chapter 1, that always returns 42. Let's rewrite it, this time in a C++ file.

The file's components are:

  1. An "#include" directive to get access to Rcpp functionality.
  2. A using namespace declaration, for convenient typing.
  3. The function definition.
  4. An Rcpp R comment block, to call the function once the C++ code is compiled.

This exercise is part of the course

Optimizing R Code with Rcpp

View Course

Exercise instructions

  • Include the Rcpp.h header file.
  • Declare that you use the Rcpp namespace.
  • Make the function return 42.
  • In the Rcpp R comment block, call the function.

Hands-on interactive exercise

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

// Include the Rcpp.h header
#include <___>

// Use the Rcpp namespace
using ___ ___;

// [[Rcpp::export]]
int the_answer() {
    // Return 42
    return ___;
}

/*** R
# Call the_answer() to check you get the right result
___
*/
Edit and Run Code