当与all()结合时,Rcpp中的is_NA()

时间:2018-01-12 17:55:45

标签: r rcpp

有没有人可以告诉我为什么以下代码返回TRUE。这让我很困惑。

> require(Rcpp)
Loading required package: Rcpp
Warning message:
package ‘Rcpp’ was built under R version 3.3.3 
> src12 <- '
+ #include <Rcpp.h>
+ using namespace Rcpp;
+ 
+ // [[Rcpp::plugins("cpp11")]]
+ 
+ // [[Rcpp::export]]
+ bool is_naFUN() {
+ 
+ LogicalVector y = {TRUE,FALSE};
+ bool x = is_na(all(y == NA_LOGICAL));
+ 
+ return x;
+ }
+ '
> sourceCpp(code = src12)
> is_naFUN()
[1] TRUE

Acturaly,它来到这里。我正在学习本教程。 rcppforeveryone-functions-related-to-logical-values 如何清楚地了解Rcpp中的NA_LOGICAL?谢谢!

2 个答案:

答案 0 :(得分:3)

目前的现状是无意中导致缺失值在所有检查中传播,因为NA值具有“传染性”,因为存在特殊数据类型。此运行时错误在很大程度上是由于比较的顺序不正确。

特别是,而不是:

is_na(all(y == NA_LOGICAL))

订单应该是:

all(is_na(y))

实质上,您希望首先测试值是否为NA,然后检查所有值是否为TRUE

关于使用all()的最后一点说明,有一个特殊的模板,要求成员函数访问最终结果,以便它可以强制转换为bool。因此,我们需要添加.is_true().is_false()。有关详细信息,请参阅有关缺失值的unofficial Rcpp API部分。

固定代码

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::plugins("cpp11")]]

// [[Rcpp::export]]
bool is_na_corrected() {

  LogicalVector y = {TRUE,FALSE};
  bool x = all(is_na(y)).is_true();

  return x;
}


/***R
is_na_corrected()
*/

结果

is_na_corrected()
# [1] FALSE

答案 1 :(得分:2)

some_bool == NA总是在R或Rcpp中返回NA,因为你不知道输入后面是什么,所以你不知道输出。

然而,R很聪明地知道NA || TRUETRUE,例如。