简体   繁体   中英

Modify SEXP in-place with Rcpp sugar

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM