14 - 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 [@vargassepulveda25]. 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, 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".

References



Try the cpp4r package in your browser

Any scripts or data that you put into this service are public.

cpp4r documentation built on Sept. 23, 2026, 5:06 p.m.