To use Armadillo classes (like arma::mat or arma::colvec) in a C++ file intended for R, you must include the appropriate header and declare the dependency using an Rcpp attribute.
For faster compilation, you can use the #include <RcppArmadillo/Lighter> header instead of the standard RcppArmadillo header. This uses the Rcpp/Lighter mechanism which excludes some heavy compile-time features (like 'Rcpp Modules') to save approximately 15% of total compilation time.
Key requirements:
- Include
<RcppArmadillo/Lighter> or <RcppArmadillo>. - Use the
// [[Rcpp::depends(RcppArmadillo)]] attribute to ensure the R environment provides the necessary headers and linking.
#include <RcppArmadillo/Lighter>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
Rcpp::List fastLm(const arma::mat& X, const arma::colvec& y) {
int n = X.n_rows, k = X.n_cols;
arma::colvec coef = arma::solve(X, y); // fit model y ~ X
arma::colvec res = y - X*coef; // residuals
double s2 = arma::dot(res, res) / (n - k); // std.errors of coefficients
arma::colvec std_err = arma::sqrt(s2 * arma::diagvec(arma::pinv(arma::trans(X)*X)));
return Rcpp::List::create(Rcpp::Named("coefficients") = coef,
Rcpp::Named("stderr") = std_err,
Rcpp::Named("df.residual") = n - k);
}