在like中是否有“适当的”NAND算子,比如
nand(condition1, condition 2)或者这仅仅是最好的实践/唯一的可能。
!(condition1 & condition2)还有其他选择吗?
发布于 2016-02-03 20:58:45
为了解决这一问题,R中没有内置的nand函数,我认为改进建议的!(x & y)的唯一方法是将这个操作移到编译语言中。
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::LogicalVector nand(Rcpp::LogicalVector lhs, Rcpp::LogicalVector rhs) {
R_xlen_t i = 0, n = lhs.size();
Rcpp::LogicalVector result(n);
for ( ; i < n; i++) {
result[i] = !(lhs[i] && rhs[i]);
}
return result;
}
/*** R
Lhs <- rbinom(10e4, 1, .5)
Rhs <- rbinom(10e4, 1, .5)
r_nand <- function(x, y) !(x & y)
all.equal(nand(Lhs, Rhs), r_nand(Lhs, Rhs))
#[1] TRUE
microbenchmark::microbenchmark(
nand(Lhs, Rhs), r_nand(Lhs, Rhs),
times = 200L)
#Unit: microseconds
# expr min lq mean median uq max neval
# nand(Lhs, Rhs) 716.140 749.926 1215.353 771.015 1856.734 6332.284 200
#r_nand(Lhs, Rhs) 3337.494 3397.809 5106.614 3461.845 4985.807 95226.834 200
*/这是否值得,这很可能取决于您需要多长时间调用nand。就大多数目的而言,上述r_nand应该足够了。实际上,base::xor的实现类似于:
base::xor
#function (x, y)
#{
# (x | y) & !(x & y)
#}
#<bytecode: 0x2fbbb90>
#<environment: namespace:base>https://stackoverflow.com/questions/35186933
复制相似问题