Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return NA via RCpp

Tags:

r

rcpp

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;
}
like image 473
uday Avatar asked Dec 08 '22 07:12

uday


2 Answers

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.

like image 117
Romain Francois Avatar answered Jan 04 '23 15:01

Romain Francois


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.

like image 33
Dirk Eddelbuettel Avatar answered Jan 04 '23 15:01

Dirk Eddelbuettel