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