Reputation: 105
I want to write an Rcpp function with a NumericMatrix argument. It returns true if any of the matrix elements are NA, false otherwise. I tried looping is_na over all the columns but I am looking for a neater way. I am also concerned about speed.
bool check(NumericMatrix M){
n=M.ncol();
for(int i=0; i < n; i ++){
if(is_na( M(_,i) ){ return T;}
}
return F;
}
Upvotes: 1
Views: 235
Reputation: 20746
Rcpp sugar can replicate the operation by combining is_na()
and any()
. is_na()
will detect missing values and any()
verifies a single value is TRUE
. Note, to retrieve a boolean value, any()
must be used with is_true()
.
#include<Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
bool contains_na(NumericMatrix M){
return is_true(any(is_na(M)));
}
Test case:
A = matrix(1:4, nrow = 2)
contains_na(A)
# [1] FALSE
M = matrix(c(1, 2, NA, 4), nrow = 2)
contains_na(M)
# [1] TRUE
Upvotes: 5