Search code examples
rrcppsuppress-warningsrcpparmadillo

Is there a way to mute warning in RcppArmadillo `arma::solve`?


When X is singular, the following code throws a warning. Is there a way of muting it?

"warning: solve(): system seems singular; attempting approx solution"

Function:

// [[Rcpp::depends(RcppArmadillo)]]


#include <RcppArmadillo.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector fastLM(const NumericVector & y_, const NumericMatrix&  X_) {
  
  const arma::vec & y = as<arma::vec>(wrap(y_));
  const arma::mat & X = as<arma::mat>(wrap(X_));

  int n = X.n_rows, k = X.n_cols;

  arma::colvec coef = arma::solve(X, y);

  return(
    as<NumericVector>(wrap(coef))
  );
}

Thank you


Solution

  • It's possible to use #define ARMA_DONT_PRINT_ERRORS but that will stop printing all errors and warnings from all functions.

    A more targeted approach would be to use options to the solve() function, like so:

    arma::colvec coef;
    
    bool success = arma::solve(coef, X, y, arma::solve_opts::no_approx);
    
    // if success is true coef is valid
    // if success is false, coef is invalid
    

    If you want to keep solutions that are singular to working precision, add another option:

    bool success = arma::solve(coef, X, y, arma::solve_opts::no_approx + solve_opts::allow_ugly);