The hardware and bandwidth for this mirror is donated by dogado GmbH, the Webhosting and Full Service-Cloud Provider. Check out our Wordpress Tutorial.
If you wish to report a bug, or if you are interested in having us mirror your free-software or open-source project, please feel free to contact us at mirror[@]dogado.de.

14 - Linear Algebra

1 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 SepulvedaSchneider Malamud 2025. One of the nicest Armadillo features is that it has a similar syntax to MATLAB.

2 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, this vignette will not repeat them here.

Here is 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 the cpp4r concepts already covered:

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;
}

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

[[cpp4r::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 (and cpp4r) with Armadillo, allowing you to use the as_Mat() and as_doubles_matrix() functions as the “bread” of the sandwich, where pure Armadillo code serves as the “meat”.

3 References

Vargas Sepulveda M, Schneider Malamud J (2025). “cpp11armadillo: An R package to use the Armadillo C++ library.” SoftwareX, 30, 102087. ISSN 2352-7110. doi:10.1016/j.softx.2025.102087. https://www.sciencedirect.com/science/article/pii/S2352711025000548.

These binaries (installable software) and packages are in development.
They may not be fully stable and should be used with caution. We make no claims about them.
Health stats visible at Monitor.