谁能告诉我为什么下面的代码返回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实际上,它就在这里。我正在学习教程。rcppforeveryone-functions-related-to-logical-values如何对Rcpp中的NA_LOGICAL有清晰的认识?谢谢!
发布于 2018-01-13 08:43:59
目前的现状无意中导致缺失值通过所有检查传播,因为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] FALSEhttps://stackoverflow.com/questions/48231661
复制相似问题