NA values in Rcpp conditional

允我心安 提交于 2019-12-05 20:59:47

问题


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

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.


回答1:


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


来源:https://stackoverflow.com/questions/11555818/na-values-in-rcpp-conditional

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!