Rcpp 条件下的 NA 值 [英] NA values in Rcpp conditional

查看:39
本文介绍了Rcpp 条件下的 NA 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rcpp 中遇到条件问题.解释我的问题的最好方法是通过一个例子.

I am having trouble with conditionals in Rcpp. The best way to explain my problem is through an example.

z <- seq(from=1,to=10,by=0.1)
z[c(5,10,15,20,40,50,80)] <- NA
src <- '
 Rcpp::NumericVector vecz(z);
 for (int i=0;i<vecz.size();i++) {
   if (vecz[i] == NA_REAL) {
     std::cout << "Here is  a missing value" << std::endl;
   }
  }
'
func <- cxxfunction(signature(z="numeric"),src,plugin="Rcpp")
func(z)
# NULL

根据我的理解,NA_REAL 表示 Rcpp 中实数的 NA 值,NA_Integer 表示整数的 NA 值.我不确定为什么给定 z,上述条件永远不会返回 true.

From my understanding, NA_REAL represents the NA values for the reals in Rcpp and NA_Integer represents the NA values for integers. I'm not sure why the above conditional never returns true given z.

推荐答案

您可能想要使用 R C 级函数 R_IsNA.

You might want to use the R C level function R_IsNA.

require(Rcpp)
require(inline)
z <- seq(from=1, to=10, by=0.1)
z[c(5, 10, 15, 20, 40, 50, 80)] <- NA

src <- '
 Rcpp::NumericVector vecz(z);
 for (int i=0; i< vecz.size(); i++) {
   if (R_IsNA(vecz[i])) {
     Rcpp::Rcout << "missing value at position " << i + 1  << std::endl;
   }
  }
'

func <- cxxfunction(signature(z="numeric"), src, plugin="Rcpp")

## results
func(z)

missing value at position 5
missing value at position 10
missing value at position 15
missing value at position 20
missing value at position 40
missing value at position 50
missing value at position 80
NULL

这篇关于Rcpp 条件下的 NA 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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