Closed asardaes closed 5 years ago
a) What type? double
aka numeric
? C++ has you covered.
b) Other types? See the R sources and cover the bit pattern to a header of your choice.
This should allow the comparison without requiring R iself and any and all gc events.
I.e. what I meant what something along these lines (turn C++11 on if needed, my compiler has it by default)
R> Rcpp::cppFunction("bool myCheck(const double x) { return std::isfinite(x); }")
R> myCheck(NA)
[1] FALSE
R> myCheck(NaN)
[1] FALSE
R> myCheck(Inf)
[1] FALSE
R> myCheck(1L)
[1] TRUE
R>
You can also check for just NaN
which, if memory serves, also catches the NA
R uses but I am a little rusty on the details -- they may be identical apart from a high bit or some other cleverness.
Ideally I'd like to use something that covers all types of NA
that R uses.
In this answer it was suggested to use something like the following to compare bit patterns
int nb_na7( const NumericVector& x){
const long long* p = reinterpret_cast<const long long*>(x.begin()) ;
long long na = *reinterpret_cast<long long*>(&NA_REAL) ;
return std::count(p, p + x.size(), na ) ;
}
but someone mentioned some parts would "violate C++ strict aliasing rules and are therefore invalid C++".
Note that R's NA
is a specific type of IEE 754 NaN
; checking for that specific bit-pattern may or may not be what you want.
All that said the various R APIs here should be safe as they do not allocate or touch the R garbage collector or other R global variables.
Thanks, everyone. I have been doing some limited tests with Rcpp::Vector<RTYPE>::is_na
and haven't run into problems.
My Google search led me to contradicting answers. Is it possible to use the
Rcpp
versions ofis_na
inside threads? Even if it is, would there be a faster way to check forNA
?