1

I am new to Rcpp and experimenting it at the moment. In a toy code, I tried to replace a even number in a vector by the number times 2.

In one case I used NumericVector as input and output data types, and in another case I used IntegerVector.

#include <Rcpp.h>
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
NumericVector replaceEven(NumericVector x) {

  for (int i = 0; i < x.length(); i++) {
    if (fmod(x[i], 2) == 0) {
      x[i] = x[i] * 2;
    }
  }
  return x;
}

sourceCpp("RcppReplaceEven.cpp")
> y = c(1,2,3,4)
> replaceEven(y)
[1] 1 4 3 8
> y
[1] 1 4 3 8

However, after replacing NumericVector by IntegerVector, the result is

> y = c(1,2,3,4)
> replaceEven(y)
[1] 1 4 3 8
> y
[1] 1 2 3 4

Just wondering why this is the case.

Fred
  • 579
  • 2
  • 4
  • 13
  • That has been discussed a few times before. In one case you "cast" to another type which creates a copy -- no change to the incoming variable as it got copied. In the other case, because it internally comes as a pointer, gets change. Look at `clone()` for an alternative. – Dirk Eddelbuettel Jul 10 '18 at 04:12
  • Where does cast come from? – Fred Jul 10 '18 at 04:15
  • No, it is your function `replaceEven()`. Please look at some Rcpp answers here containing `clone()`. – Dirk Eddelbuettel Jul 10 '18 at 04:17
  • In another case, it is IntegerVector replaceEven (IntegerVector x). Both input and outputs are IntegerVectors. Why is there a cast in this case? Thanks. – Fred Jul 10 '18 at 04:19
  • [This post](https://zenglix.github.io/Rcpp_basic/) might be useful, in particular the sub-section `NumericVector` in section `Rcpp Data Structure`. – Maurits Evers Jul 10 '18 at 04:20
  • @Fred I talk about your problem in these 2 slides: https://privefl.github.io/R-presentation/Rcpp.html#29 – F. Privé Jul 10 '18 at 04:31
  • 1
    I think I get it now. I forgot y=c(1,2,3,4) was actually a numeric vector. If using y=c(1L, 2L, 3L, 4L), then the result will be the one expected. – Fred Jul 10 '18 at 04:54

0 Answers0