is_NA() 在 Rcpp 中与 all() 结合使用
is_NA() in Rcpp when combined with all()
有谁能告诉我为什么以下代码 return 正确。这让我很困惑。
> 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?谢谢!
some_bool == NA
在 R 或 Rcpp 中总是返回 NA
,因为你不知道输入背后的内容,所以你不知道输出。
然而,R 足够聪明,知道 NA || TRUE
是 TRUE
,例如。
目前的现状无意中导致缺失值通过所有检查传播,因为 NA
值是 "contagious",因为存在特殊的数据类型。这个运行时错误在很大程度上是由于比较的顺序不正确造成的。
特别是,而不是做:
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
有谁能告诉我为什么以下代码 return 正确。这让我很困惑。
> 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?谢谢!
some_bool == NA
在 R 或 Rcpp 中总是返回 NA
,因为你不知道输入背后的内容,所以你不知道输出。
然而,R 足够聪明,知道 NA || TRUE
是 TRUE
,例如。
目前的现状无意中导致缺失值通过所有检查传播,因为 NA
值是 "contagious",因为存在特殊的数据类型。这个运行时错误在很大程度上是由于比较的顺序不正确造成的。
特别是,而不是做:
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