Linear Algebra

Motivation

R provides out-of-box support for matrices and vectors. This is not the case for C++ code, where you need to use a library such as Armadillo that has a wrapper for R (Vargas Sepulveda and Schneider Malamud 2025). One of the nicest Armadillo features is that it has a similar syntax to MATLAB.

Using Armadillo

cpp11armadillo provides a detailed R-specific documentation with worked examples.

Because the examples in the cpp11armadillo are self-contained and with detailed explanations, we will not repeat them here.

Here one of the over five-hundred examples from the cpp11armadillo package to compute \(\hat{\beta} = (X^TX)^{-1}X^Ty\) for a linear model using what we already covered about cpp11:

Mat<double> ols_(const doubles_matrix<>& y, const doubles_matrix<>& x) {
  Mat<double> Y = as_Mat(y);  // Col<double> Y = as_Col(y); also works
  Mat<double> X = as_Mat(x);

  Mat<double> XtX = X.t() * X;             // X'X
  Mat<double> XtX_inv = inv(XtX);          // (X'X)^(-1)
  Mat<double> beta = XtX_inv * X.t() * Y;  // (X'X)^(-1)(X'Y)

  return beta;
}

[[cpp11::register]] doubles_matrix<> ols_mat_(const doubles_matrix<>& y,
                                              const doubles_matrix<>& x) {
  Mat<double> beta = ols_(y, x);
  return as_doubles_matrix(beta);
}

[[cpp11::register]] doubles ols_dbl_(const doubles_matrix<>& y,
                                     const doubles_matrix<>& x) {
  Mat<double> beta = ols_(y, x);
  return as_doubles(beta);
}

One of the advantages of cpp11armadillo is that it connects cpp11 with Armadillo, so you can use the as_Mat() and as_doubles_matrix() functions to be the “bread” of the sandwich, where pure Armadillo code is the “meat”.

References

Vargas Sepulveda, Mauricio, and Jonathan Schneider Malamud. 2025. “Cpp11armadillo: An R Package to Use the Armadillo C++ Library.” SoftwareX 30 (May): 102087. https://doi.org/10.1016/j.softx.2025.102087.