Rcpp function check if missing value

前端 未结 3 932
鱼传尺愫
鱼传尺愫 2020-12-03 00:24

I\'m converting R based code into Rcpp based code. The head of my function is:

NumericMatrix createMatrixOfLinkRatiosC(NumericMatrix matr, double threshold4C         


        
3条回答
  •  無奈伤痛
    2020-12-03 00:48

    Both Rcpp and RcppArmadillo have predicates to test for NA, NaN (an R extension) and Inf.

    Here is a short RcppArmadillo example:

    #include 
    
    // [[Rcpp::depends(RcppArmadillo)]]
    
    // [[Rcpp::export]]
    arma::mat foo(int n, double threshold=NA_REAL) {
      arma::mat M = arma::zeros(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> 
    

提交回复
热议问题