Search code examples
c++rrcpp

Conditional update of NumericVectors in Rcpp


In R, I would use this to update values in a vector matching a conditional criteria:

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

How would I go about doing this using Rcpp if i had a NumericVector of a?

I am new to Rcpp and the only way I can think of at the moment is to loop over each value in a. I am using this:

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);

}')

Is there a way of doing this without the loop or with fewer lines of code?

Any help much appreciated.


Solution

  • For standard algorithms like this one, you may find it already implemented in the standard library:

    #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
    */
    

    Beware that if input a is already of type double, it will get modified.