LoslegenKostenlos loslegen

R code in C++ files

When you compile your C++ file with sourceCpp() (or the "Source" button in RStudio), Rcpp compiles your code and makes the exported functions available as R functions.

sourceCpp() also treats comments between /*** R and */ as R code to be executed once the code is compiled.

/*** R
# Run the exported R code here
*/

This is particularly useful when you are developing your code because you can very quickly test the effects of changes to your code.

You will use these special comments throughout the rest of this course.

Diese Übung ist Teil des Kurses

Optimizing R Code with Rcpp

Kurs anzeigen

Anleitung zur Übung

  • Start an Rcpp R comment block with /*** R.
  • Call the dist function to calculate the distance from the origin to the (3,4) point.
  • Close the Rcpp R comment block with */.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

#include 
using namespace Rcpp; 

double square(double x) {
  return x * x ;
}

// [[Rcpp::export]]
double dist(double x, double y) {
  return sqrt(square(x) + square(y));
}

// Start the Rcpp R comment block
___
# Call dist() to the point (3, 4)
___
# Close the Rcpp R comment block
___
Code bearbeiten und ausführen