我在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给定z
。
答案 0 :(得分:14)
您可能想要使用R C级功能 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