9

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

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 值。我不确定为什么上述条件永远不会返回 true given z

4

1 回答 1

16

您可能想要使用 RC 级别函数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
于 2012-07-19T09:52:33.027 回答