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 (cpp4rarmadillo?). One of the nicest Armadillo features is that it has a similar syntax to MATLAB.
Using Armadillo
cpp4rarmadillo provides a detailed R-specific documentation with worked examples.
Because the examples in the cpp4rarmadillo 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 cpp4rarmadillo package to compute 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 cpp4rarmadillo is that it connects 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”.