Rcpp

36.1 Inline C++ functions

library(Rcpp)

cppFunction('
double sumC(NumericVector x) {
  double total = 0;
  for (int i = 0; i < x.size(); ++i) total += x[i];
  return total;
}')

sumC(c(1, 2, 3))   # 6

36.2 Source files

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int fibC(int n) {
  if (n < 2) return n;
  return fibC(n - 1) + fibC(n - 2);
}

// [[Rcpp::export]]
NumericVector cumsumC(NumericVector x) {
  NumericVector out(x.size());
  double acc = 0;
  for (int i = 0; i < x.size(); ++i) { acc += x[i]; out[i] = acc; }
  return out;
}

// [[Rcpp::export]]
DataFrame summarize_df(DataFrame df) {
  NumericVector v = df["value"];
  return DataFrame::create(_["mean"] = mean(v), _["max"] = max(v));
}
sourceCpp("fib.cpp")
fibC(30)            # orders of magnitude faster than the R version

36.3 Rcpp types & sugar

NumericVector, IntegerVector, CharacterVector, LogicalVector, List, DataFrame, NumericMatrix, Function, Environment. Rcpp sugar gives vectorized R-like syntax in C++ (sum(x), ifelse(x > 0, x, 0), rnorm(n)).

36.4 Related tools

RcppArmadillo / RcppEigen — linear algebra.

RcppParallel — parallel loops.

cpp11 — header-only modern C++ interface (used by tidyverse packages).

.Call / .C / .External — the raw C API (R.h, Rinternals.h).

extendr — write R extensions in Rust; savvy alternative.

Fortran via .Fortran(); dotcall64.