r-在Rcpp中检查向量的零和NA

  • 本文关键字:NA 向量 Rcpp r rcpp
  • 更新时间 :
  • 英文 :


我试图根据第二个可为空向量(r(的值是否为NA来计算向量(y(的和。如果第二矢量r为NULL,则应将y的所有值相加。如果r的所有元素都是NA,则函数应返回NA。有关所需输出,请参阅文本末尾。

我首先尝试了以下代码:

library(Rcpp)
cppFunction('double foo(NumericVector y, Rcpp::Nullable<Rcpp::IntegerVector> r = R_NilValue) {
  double output = 0;
  bool return_na = !Rf_isNull(r);
  int y_count = y.size();
  for (int i = 0; i < y_count; i++) {
    if (Rf_isNull(r)  || !R_IsNA(r[i])) {
    //// if (Rf_isNull(r)  || !R_IsNA(as<IntegerVector>(r)[i])) {
      if (!Rf_isNull(r))
        Rcout << R_IsNA(as<IntegerVector>(r)[i]) << " - "<< as<IntegerVector>(r)[i] << std::endl;
      output = output + y[i];
      return_na = false;
    } 
  }
  if (return_na) 
    return NA_REAL;
  return output;
}')

这给了我以下错误:

 error: invalid use of incomplete type 'struct SEXPREC'
     if (Rf_isNull(r)  || !R_IsNA(r[i])) {
                                     ^

为了解决这个问题,我使用了if (Rf_isNull(r) || !R_IsNA(as<IntegerVector>(r)[i])) {。但这一次,当转换为整数向量时,NA值被转换为数字,R_IsNA()测试给出假阳性。

这是我想要的预期输出。

foo(1:4, NULL) #  <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, 1, 1)) #  <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, NA, 1)) #  <- This should return 7 = 1 + 2 + 4
foo(1:4, c(NA, NA, NA, NA)) # <- This should return NA

如何获得我想要的函数?(这个例子被简化了,我对和函数不是特别感兴趣。相反,我感兴趣的是像例子中给出的那样同时检查NANULL。(

三个建议:

  • 使用Rcpp而不是R的C API
  • rNULL时提前返回
  • 在循环输入向量之前创建一个LogicalVector
#include <Rcpp.h>
// [[Rcpp::export]]
double foo(Rcpp::NumericVector y, Rcpp::Nullable<Rcpp::IntegerVector> r = R_NilValue) {
    if (r.isNull())
        return Rcpp::sum(y);
    Rcpp::LogicalVector mask = Rcpp::is_na(r.as());
    if (Rcpp::is_true(Rcpp::all(mask))) 
        return NA_REAL;
    double output = 0.0;
    int y_count = y.size();
    for (int i = 0; i < y_count; ++i) {
        if (!mask[i]) {
            output += y[i];
        } 
    }
    return output;
}
/***R
foo(1:4, NULL) #  <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, 1, 1)) #  <- This should return 10 = 1 + 2 + 3 + 4
foo(1:4, c(1, 1, NA, 1)) #  <- This should return 7 = 1 + 2 + 4
foo(1:4, c(NA, NA, NA, NA)) # <- This should return NA
*/ 

结果:

> Rcpp::sourceCpp('60569482.cpp')
> foo(1:4, NULL) #  <- This should return 10 = 1 + 2 + 3 + 4
[1] 10
> foo(1:4, c(1, 1, 1, 1)) #  <- This should return 10 = 1 + 2 + 3 + 4
[1] 10
> foo(1:4, c(1, 1, NA, 1)) #  <- This should return 7 = 1 + 2 + 4
[1] 7
> foo(1:4, c(NA, NA, NA, NA)) # <- This should return NA
[1] NA

进一步建议:

  • 使用掩码进行子设置y
#include <Rcpp.h>
// [[Rcpp::export]]
double foo(Rcpp::NumericVector y, Rcpp::Nullable<Rcpp::IntegerVector> r = R_NilValue) {
    if (r.isNull())
        return Rcpp::sum(y);
    Rcpp::LogicalVector mask = Rcpp::is_na(r.as());
    if (Rcpp::is_true(Rcpp::all(mask))) 
        return NA_REAL;
    Rcpp::NumericVector tmp = y[!mask];
    return Rcpp::sum(tmp);
}

最新更新