1

I'm having problems with a simple code in Rcpp. My problem is that I want to change a vector by passing it to a function. A example is:

//[[Rcpp::export]]
void ones(IntegerVector x, int lx){
   int i;
   for(i = 0; i < lx; i++){
       x(i) = 1;
   }
}

When I do in R:

x = rep(-1, 10)
ones(x, length(x))

the vector x do not change. How can i work this out?

edit: If I pass x as &x how do I change it's values?

edit: after trying the two methods proposed in the first two answers nothing changed.

edit: restarted Rstudio and now it works....... Is it a common problem for Rstudio users?

Mur1lo
  • 111
  • 1
  • 4

1 Answers1

5

Actually, you can do this without passing by reference since Rcpp classes are proxy objects, but you must pass exactly the correct type of vector. In your function signature, x is an IntegerVector, but you pass in a NumericVector since rep(-1, 10) returns a numeric, not an integer. Because of the type mismatch, the input had to be coerced to an IntegerVector, meaning a copy was created, and the original (numeric vector) was not modified. For example,

#include <Rcpp.h>

// [[Rcpp::export]]
void ones(Rcpp::IntegerVector x, int lx) {
   for (int i = 0; i < lx; i++) {
       x[i] = 1;
   }
}

/*** R

x <- rep(-1, 10)
class(x)
#[1] "numeric"

ones(x, length(x))
x
#[1] -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

y <- as.integer(rep(-1, 10)) # or, rep(-1L, 10)
class(y)
#[1] "integer"

ones(y, length(y))
y
#[1] 1 1 1 1 1 1 1 1 1 1

*/ 

Similarly, if x were typed as a NumericVector in your function signature, the coercion to integer would not be needed:

#include <Rcpp.h>

// [[Rcpp::export]]
void ones_numeric(Rcpp::NumericVector x, int lx) {
   for (int i = 0; i < lx; i++) {
       x[i] = 1.0;
   }
}

/*** R

z <- rep(-1, 10)
class(z) 
#[1] "numeric"

ones_numeric(z, length(z))
z
#1] 1 1 1 1 1 1 1 1 1 1

*/
nrussell
  • 18,382
  • 4
  • 47
  • 60