问题
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;
}
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/23744114/return-na-via-rcpp