【问题标题】:return NA via RCpp通过 RCpp 返回 NA
【发布时间】:2014-05-19 17:51:27
【问题描述】:

这里的新手 RCpp 问题:如何让 NumericVector 返回NA 到 R?例如,假设我有一个将NA 分配给向量的第一个元素的 RCpp 代码。

// [[RCpp::export]]
NumericVector myFunc(NumericVector x) {
   NumericVector y=clone(x);
   y[0]=NA; // <----- what's the right expression here?
   return y;
}

【问题讨论】:

    标签: r rcpp


    【解决方案1】:

    为给定的向量类型(NumericVectorIntegerVector、...)获取正确的NA 的规范方法是使用静态get_na 方法。类似的东西:

    y[0] = NumericVector::get_na() ;
    

    FWIW,您的代码与Rcpp11 一样工作,它知道如何从静态Na_Proxy 实例NA 转换为目标类型的正确缺失值。

    【讨论】:

    • 顺便说一句,在 Rcpp 中具有相同的行为是微不足道的。
    • 谢谢,太好了。这可能是一种较短的写作方式:NumericVector y=no_init(n); for (int i=0;i&lt;n;i++) { y[i]=NA_REAL;},例如y=NumericVector::get_na().
    • get_na 为您提供单个值。您可以使用NumericVector y = rep( NumericVector::get_na(), n )NumericVector y(n, NumericVector::get_na() ) ;,例如,如果您想要一个大小为n 的NA 向量。
    【解决方案2】:

    请至少尝试通过我们的回归测试提供的大量示例进行 grep:

    edd@max:~$ cd  /usr/local/lib/R/site-library/Rcpp/unitTests/cpp/
    edd@max:/usr/local/lib/R/site-library/Rcpp/unitTests/cpp$ grep NA *cpp | tail -5
    support.cpp:           Rf_pentagamma( NA_REAL) ,
    support.cpp:           expm1( NA_REAL ),
    support.cpp:           log1p( NA_REAL ),
    support.cpp:           Rcpp::internal::factorial( NA_REAL ),
    support.cpp:           Rcpp::internal::lfactorial( NA_REAL )
    edd@max:/usr/local/lib/R/site-library/Rcpp/unitTests/cpp$ 
    

    此外,这实际上是一个针对 R 的 C 问题,并在编写 R 扩展手册中得到了解答。

    您也可以在this Rcpp Gallery post 和其他人中找到一个很好的例子; Rcpp Gallery有搜索功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多