Rcpp 中 NumericVectors 的条件更新

Conditional update of NumericVectors in Rcpp

R 中,我将使用它来更新与条件条件匹配的向量中的值:

a <- rep(seq(1:20),5)
a[a==5] <- 100 

如果我有 a 的 NumericVector,我将如何使用 Rcpp 执行此操作?

我是 Rcpp 的新手,目前我能想到的唯一方法是遍历 a 中的每个值。我正在使用这个:

cppFunction('NumericVector test(NumericVector a){
            int b = a.size();
            for (int i = 0; i < b; i++) {
            if (a[i] == 5) {
            a[i] = 100;
            }
      }
      return(a);

}')

有没有一种方法可以不用循环或用更少的代码行来做到这一点?

非常感谢任何帮助。

对于像这样的标准算法,您可能会发现它已经在标准库中实现了:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector replace(NumericVector x) {
  std::replace(x.begin(), x.end(), 5, 100);
  return x;
}


/*** R
a <- rep(seq(1:20),5)
replace(a)
a
*/

请注意,如果输入 a 已经是 double 类型,它将被修改。