【问题标题】:Return NA from Rcpp从 Rcpp 返回 NA
【发布时间】:2020-11-14 03:25:36
【问题描述】:

我正在尝试通过 Rcpp 返回 NA。我不明白为什么 get_na() 不能按照 post 中的建议在这里工作?

> Rcpp::cppFunction('NumericVector temp1() {
   return NumericVector::get_na();
 }')
> temp1()
Error in temp1() : negative length vectors are not allowed

如果我尝试create(),它会起作用。

> Rcpp::cppFunction('NumericVector temp2() {
    return NumericVector::create(NA_REAL);
  }')
> temp2()
  NA

【问题讨论】:

    标签: r rcpp


    【解决方案1】:

    您需要执行以下操作:

    Rcpp::cppFunction('NumericVector temp1() {
      NumericVector y(1);
      y[0] = NumericVector::get_na();
      return y;
    }')
    
    temp1()
    #R> [1] NA
    

    如果你想使用NumericVector::get_na()。请注意,this member function 只是返回 NA_REAL,这就是为什么您可能会在 NumericVector 的构造函数中遇到错误:

    Rcpp::cppFunction('NumericVector temp1() {
       return NumericVector::get_na();
     }')
    

    您同样可以按照您的建议使用NumericVector::create。你也可以这样做:

    Rcpp::cppFunction('NumericVector temp2() {
      return NumericVector(1, NA_REAL);
    }')
    

    Rcpp::cppFunction('double temp3() {
      return NA_REAL;
    }')
    

    从 Rcpp 返回 NA

    如果您正在处理其他类型的向量,那么NumericVectorget_na 函数会非常有用。这是一个示例,其中我们返回 NA,但根据输入具有不同的类型。

    Rcpp::sourceCpp(code = '
      #include "Rcpp.h"
      using namespace Rcpp;
      
      template<int T>
      Vector<T> get_na_genric(){
        return Vector<T>(1, Vector<T>::get_na());
      }
      
      // [[Rcpp::export]]
      SEXP get_nan_vec(SEXP x) {
        switch (TYPEOF(x)) {
          case INTSXP : return get_na_genric<INTSXP >();
          case LGLSXP : return get_na_genric<LGLSXP >();
          case REALSXP: return get_na_genric<REALSXP>();
          case STRSXP : return get_na_genric<STRSXP >();
          case VECSXP : return get_na_genric<VECSXP >();
          stop("type not implemented");
        }
        
        return get_na_genric<REALSXP>();
      }')
    
    for(x in list(integer(), logical(), numeric(), character(), 
                  list())){
      out <- get_nan_vec(x)
      cat("got:\n")
      print(out)
      cat("with type ", typeof(out), "\n")
    }
    #R> got:
    #R> [1] NA
    #R> with type  integer 
    #R> got:
    #R> [1] NA
    #R> with type  logical 
    #R> got:
    #R> [1] NA
    #R> with type  double 
    #R> got:
    #R> [1] NA
    #R> with type  character 
    #R> got:
    #R> [[1]]
    #R> NULL
    #R> 
    #R> with type  list 
    

    【讨论】:

    • 不错的答案。一个重要问题是 NA 一个值,因此您必须按照答案所示进行分配,并且 OP 的原始 create() 方法也是如此。
    • 感谢您的详细回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多