Consider a dummy example
> cppFunction('
+ NumericVector invert(NumericVector& x) {
+ x = x + 1;
+ return x;
+ }')
> invert(1:3)
[1] 2 3 4
Rcpp sugar is convenient, but presumably inefficient, because it creates a new object and assigns it instead of modifying the original one in-place. Intuitively, I attempted to do a x += 1;
, but Rcpp complains
error: no viable overloaded '+='
How can I use Rcpp sugar to perform in-place modification?
Your assumption is wrong -- no copies are made [1]. So just do it in-place:
R> library(Rcpp)
R> cppFunction("void inplaceMod(NumericVector x) { x = x + 1; }")
R> x <- as.numeric(1:5)
R> inplaceMod(x)
R> x
[1] 2 3 4 5 6
R>
So for your question:
How can I use Rcpp sugar to perform in-place modification?
the answer is 'just use it as is' but pay attention to your object types. If you do, then the most efficient access possible is offered by direct and seamless access to the R object memory.
[1] One known and documented caveat is when a silent cast occurs. The above would not work with 1:5
as those are integers which get copied to numeric first as we have NumericVector
in the function signature. See the Rcpp FAQ, Question 5.1 and other places for more on this one.