Rcpp 函数检查是否缺失值 [英] Rcpp function check if missing value

查看:46
本文介绍了Rcpp 函数检查是否缺失值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将基于 R 的代码转换为基于 Rcpp 的代码.我的函数负责人是:

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

NumericMatrix createMatrixOfLinkRatiosC(NumericMatrix matr, double threshold4Clean) {
int i,j; 
NumericMatrix myMatr(matr.nrow(),matr.ncol());
myMatr=matr;
....;

}

我想处理对缺少 threshold4Clean 的函数的调用,但我不知道该怎么做...任何帮助将不胜感激.

I want to handle call to the function where threshold4Clean is missing but I'm not finding how to do... Any help will be greatly appreciated.

推荐答案

Rcpp 和 RcppArmadillo 都有谓词来测试 NANaN(R 扩展)和 <代码>信息.

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

这是一个简短的 RcppArmadillo 示例:

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)
***/

我们初始化一个零矩阵,并测试参数.如果它是有限的(即不是NAInfNaN),那么我们添加该值.如果您愿意,也可以单独测试各种可能性.

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.

这会产生所需的结果:没有第二个参数,NA 的默认值适用,我们得到一个零矩阵.

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> 

这篇关于Rcpp 函数检查是否缺失值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆