5

Newbie RCpp question here: how can I make a NumericVector return NA to R? For example, suppose I have a RCpp code that assigns NA to the first element of a vector.

// [[RCpp::export]]
NumericVector myFunc(NumericVector x) {
   NumericVector y=clone(x);
   y[0]=NA; // <----- what's the right expression here?
   return y;
}
uday
  • 6,453
  • 13
  • 56
  • 94

2 Answers2

8

The canonical way to get the correct NA for a given vector type (NumericVector, IntegerVector, ...) is to use the static get_na method. Something like:

y[0] = NumericVector::get_na() ;

FWIW, your code works as is with Rcpp11, which knows how to convert from the static Na_Proxy instance NA into the correct missing value for the target type.

Romain Francois
  • 17,432
  • 3
  • 51
  • 77
  • And BTW, it would be trivial to have the same behavior in Rcpp. – Romain Francois May 19 '14 at 19:26
  • Thanks, that's great. It might be a shorter way of writing: `NumericVector y=no_init(n); for (int i=0;i – uday May 19 '14 at 19:44
  • 1
    `get_na` gives you a single value. You can use `NumericVector y = rep( NumericVector::get_na(), n )` or `NumericVector y(n, NumericVector::get_na() ) ;` for example if you want a vector of NA of size `n`. – Romain Francois May 19 '14 at 19:46
7

Please at least try to grep through the large corpus of examples provided by our regression tests:

edd@max:~$ cd  /usr/local/lib/R/site-library/Rcpp/unitTests/cpp/
edd@max:/usr/local/lib/R/site-library/Rcpp/unitTests/cpp$ grep NA *cpp | tail -5
support.cpp:           Rf_pentagamma( NA_REAL) ,
support.cpp:           expm1( NA_REAL ),
support.cpp:           log1p( NA_REAL ),
support.cpp:           Rcpp::internal::factorial( NA_REAL ),
support.cpp:           Rcpp::internal::lfactorial( NA_REAL )
edd@max:/usr/local/lib/R/site-library/Rcpp/unitTests/cpp$ 

Moreover, this is actually a C question for R and answered in the Writing R Extensions manual.

You could also have found a good example in this Rcpp Gallery post as well as others; there is a search function right at the Rcpp Gallery.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725