Both Rcpp and RcppArmadillo have predicates to test for NA
, NaN
(an R extension) and Inf
.
Here is a short RcppArmadillo example:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat foo(int n, double threshold=NA_REAL) {
arma::mat M = arma::zeros<arma::mat>(n,n);
if (arma::is_finite(threshold)) M = M + threshold;
return M;
}
/*** R
foo(2)
foo(2, 3.1415)
***/
We initialize a matrix of zeros, and test for the argument. If it is finite (ie not NA
or Inf
or NaN
), then we add that value. If you wanted to, you could test for the possibilities individually too.
This produces the desired result: without a second argument the default value of NA
applies, and we get a matrix of zeros.
R> Rcpp::sourceCpp("/tmp/giorgio.cpp")
R> foo(2)
[,1] [,2]
[1,] 0 0
[2,] 0 0
R> foo(2, 3.1415)
[,1] [,2]
[1,] 3.1415 3.1415
[2,] 3.1415 3.1415
R>