Source your C++ code

Source stand-alone C++ files into R using sourceCpp()

C++ files have extension .cpp

#include <Rcpp.h>
using namespace Rcpp;

And for each function that you want available within R, you need to prefix it with:

// [[Rcpp::export]]

Inside a cpp file you can include R code using special comments

/*** R
rcode here
*/

Example

This block in Rmarkdown uses {Rcpp} as a short hand for engine = “Rcpp”.

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
double meanC(NumericVector x) {
  int n = x.size();
  double total = 0;

  for(int i = 0; i < n; ++i) {
    total += x[i];
  }
  return total / n;
}

/*** R
x <- runif(1e5)
bench::mark(
  mean(x),
  meanC(x)
)
*/

NOTE: For some reason although the r code above runs, knit doesn’t include the output. Why?

x <- runif(1e5)
bench::mark(
  mean(x),
  meanC(x)
)
#> # A tibble: 2 × 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 mean(x)       390µs    437µs     2267.        0B        0
#> 2 meanC(x)      372µs    372µs     2659.        0B        0