在RCPP NumericVectors的条件更新

问题描述 投票:-4回答:1

R,我会用这个匹配条件的标准的矢量来更新值:

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

我怎么会去这样做使用Rcpp如果我有a的NumericVector?

我是新来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);

}')

是否有这样做没有循环或更少的代码的方法吗?

任何帮助非常赞赏。

c++ r rcpp
1个回答
4
投票

对于标准算法,像这样的,你会发现它已经在标准库实现的:

#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的,它会被修改。

© www.soinside.com 2019 - 2024. All rights reserved.