在 Rcpp 中使用 NumericVector 编写条件语句是否有更简单的方法?

Is there an easier way to write conditional statements with NumericVector in Rcpp?

我正在尝试使用 Rcpp 编写一些代码,并且我正在尝试了解条件语句如何在逻辑向量之间工作,因为它们是通过使用 NumericVector 和 C++ 的本机 bool 类型进行比较而产生的。

我确定的方法如下(可重现性最小的例子,我的例子比较复杂):

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]

NumericVector compare(NumericVector a, NumericVector b) {
   if (is_true(all(b <= a))) {
     return a;
   }
   return b;
}

然而,is_true 和所有这些似乎都是多余的(例如,在我没有向您展示的更复杂的情况下),a 和 b 的长度保证为 1。

现在我是不是发现了一个非常复杂的技术,或者这是一个不幸的案例“这是我们所拥有的最好的”(尽管有这样的边缘情况,但这种方法的理由比反对的理由要好) )'?

不幸的是,is_true()is_false() 需要与 all() Rcpp 糖函数一起使用,因为:

The actual return type of all(X) is an instance of the SingleLogicalResult template class, but the functions is_true and is_false may be used to convert the return value to bool.

c.f。 http://thecoatlessprofessor.com/programming/unofficial-rcpp-api-documentation/#all


解决这个问题的唯一方法是自己实现循环(@Aconcagua 暗示):

#include <Rcpp.h>

// [[Rcpp::export]]
Rcpp::NumericVector compare_loop(Rcpp::NumericVector a, Rcpp::NumericVector b) {

  if(a.size() != b.size()) Rcpp::stop("Lengths of a and b must be the same.");

  for (int i = 0; i < a.size(); ++i) {
    // take opposite of comparison or switch it to b[i] > a[i]
    if ( !(b[i] <= a[i]) ) {
      return b;
    }
  }

  return a;
}

测试:

a = c(-1, 2, 3, 5)
b = c(-3, -2, 4, 3)

all.equal(compare_loop(a,b), compare(a,b))
# [1] TRUE