Kristian Kristian - 5 months ago 26
R Question

How can I protect a matrix in R from being altered by Rcpp?

I am making a package containing two Rcpp functions. The first function is used for creating a matrix that will be used several times by the second function. The matrix is stored in R's global environment between calls to the two functions.

M <- myFirstRcpp(X)
P <- mySecondRcpp(M)

Depending on input parameters the second function will make changes to the input matrix (created by the first function) before calculating a vector from it (
is the C++ inside

IntegerVector aFunction( SEXP Qin, SEXP param ) {
NumericMatrix Q(Qin);
// Some changes made to Q
// return a vector generated from Q

My problem is that the changes done to the
matrix inside the second Rcpp function also affect the copy of the matrix (
) residing in R's global environment.

How can I prevent Rcpp from altering the global environment of R without too much overhead?

Notes: The
matrix is ~2000x65000 in size. The problem occurs with R 3.0.2 and Rcpp 0.10.6 on Windows and Linux in 32 and 64 bit R.


That is a known and documented feature. We are being called from R via the interface

  SEXP somefunction(SEXP a, SEXP b, ...)

so a pointer is being passed and changes to Q affect the outer object. That is a good thing as it makes the calls very fast -- no copies.

If you want distinct instances, use the clone() method as in

  NumericMatrix Q = clone(Qin);