[Rcpp-devel] How to modifying the elements of a list in the global environment?

Christian Gunning xian at unm.edu
Fri Oct 19 10:06:14 CEST 2012


>> ### For the Rcpp part, set aside working space in the global environment
>> workspace <- lapply(1:K, function(k) matrix(0.0, N, M))
>
> Then I try to access the matrices in the 'workspace' list and modify them, but so far I have had no success. The first attemp, bolow, does not compile...
>
>> code_f <- '
> +     Rcpp::NumericMatrix cpp_x(x);

If you're familiar with R and new to C++, understanding how C++
clone() works will help. For example, to use a single matrix as a
"working matrix" (if you write over it each iteration),  define the
working matrix (workmat) in R.   You can pass that object to the C++
function in two different ways:

Rcpp::NumericMatrix workmat(workmat_);  // modifies existing R
structure in-place, no extra copy made
Rcpp::NumericMatrix workmat( clone(workmat_) );  // allocate new
memory to make a "deep copy"

Assuming N & M are constant, then you can make a single matrix in R
and modify it in-place without any cost of extra copying.  If you
*want* and extra copy, you use clone().  R *always* makes a new copy
-- this is one of the "big divides" between R and C++,
pass-by-reference versus pass-by-value (clone).

For examples, see
http://cran.r-project.org/web/packages/Rcpp/vignettes/Rcpp-quickref.pdf.
-Christian
-- 
A man, a plan, a cat, a ham, a yak, a yam, a hat, a canal – Panama!


More information about the Rcpp-devel mailing list