编写一个 Rcpp 函数来检测 NumericMatrix 是否有任何 NA 值
Write an Rcpp function to detect if a NumericMatrix has any NA values
我想编写一个带有 NumericMatrix 参数的 Rcpp 函数。如果任何矩阵元素为 NA,则 returns 为真,否则为假。我尝试在所有列上循环 is_na 但我正在寻找一种更简洁的方法。我也很关心速度。
bool check(NumericMatrix M){
n=M.ncol();
for(int i=0; i < n; i ++){
if(is_na( M(_,i) ){ return T;}
}
return F;
}
rcpp sugar可以通过组合is_na()
和any()
来复制操作。 is_na()
将检测缺失值,any()
验证单个值是否为 TRUE
。请注意,要检索布尔值,any()
必须与 is_true()
一起使用。
#include<Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
bool contains_na(NumericMatrix M){
return is_true(any(is_na(M)));
}
测试用例:
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
我想编写一个带有 NumericMatrix 参数的 Rcpp 函数。如果任何矩阵元素为 NA,则 returns 为真,否则为假。我尝试在所有列上循环 is_na 但我正在寻找一种更简洁的方法。我也很关心速度。
bool check(NumericMatrix M){
n=M.ncol();
for(int i=0; i < n; i ++){
if(is_na( M(_,i) ){ return T;}
}
return F;
}
rcpp sugar可以通过组合is_na()
和any()
来复制操作。 is_na()
将检测缺失值,any()
验证单个值是否为 TRUE
。请注意,要检索布尔值,any()
必须与 is_true()
一起使用。
#include<Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
bool contains_na(NumericMatrix M){
return is_true(any(is_na(M)));
}
测试用例:
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