9

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.

sgibb
  • 25,396
  • 3
  • 68
  • 74
chandler
  • 716
  • 8
  • 15
  • 2
    It's never true for basically the same reason that `NA == NA` is not true in R. – hadley Nov 15 '12 at 22:37
  • What is NA_REAL then? I got caught by this primarily because x==NA_INTEGER is used in the Rcpp sugar vignette, so I figured NA_REAL would work similarly. – Ian Fellows May 07 '14 at 21:24

1 Answers1

16

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
dickoa
  • 18,217
  • 3
  • 36
  • 50
  • Compare `NA` with `NA` gives `NA`. So `x[i] == x[i]` faster then `R_IsNA(x[i])`. – Artem Klevtsov Mar 29 '16 at 14:37
  • 1
    @ArtemKlevtsov I don't think you would want to use `x[i] == x[i]` since anything compared to 'NA' is 'NA'. The best R function is going to be `is.na(x)` because even something like `identical(x, NA)` does not always work (i.e. `identical(NA_integer_, NA)` returns `FALSE`). – seasmith Jan 14 '17 at 19:57