[Rcpp-devel] Passing arguments by value: unexpected behaviour

Romain Francois romain at r-enthusiasts.com
Tue Sep 14 11:38:57 CEST 2010


Le 14/09/10 11:29, Johannes Egner a écrit :
> Romain,
>
> many thanks for the (incredibly speedy) reply.
>
>     You are missing that :
>
>      > typeof( 1:2 )
>     [1] "integer"
>
>     So as.double creates a new numeric vector, but:
>
>      > typeof( 1 )
>     [1] "double"
>
>     So as.double just returns its input. as.double is a primitive
>     function in R, so it does not really have pass by value semantics.
>
>
> Ok, I %really% should have picked up on that -- my R knowledge usually
> does stretch this far.
>
>     By design, when you create an Rcpp object, you don't get a copy of
>     the original object, you point to the same SEXP.
>
>
> Yup, I know that from the documentation.
>
>     If you want a copy, you can use clone, as in :
>
>     NumericVector vec = clone<NumericVector>(arg)
>
>
> This is a very interesting function (templated, I suppose) -- I haven't
> seen this in the examples/presentations. Thanks.

Yes. And simple too:

/* cloning type T is possible if :
    - T can be converted to SEXP
    - T has a SEXP constructor
*/
template <typename T> T clone(const T& object) {
     SEXP x = const_cast<T&>(object) ;
     return T( Rf_duplicate( x ) ) ;
}

You can also do:

NumericVector vec = ::Rf_duplicate(arg) ;

> Incidentally, I have seen you now have a cheat sheet (or quick
> reference, as it's called on CRAN). I think this is very good idea for a
> certain group of users (like me -- those that want to get results
> relatively quickly without getting into %all% the nitty-gritty details),
> and it is worth keeping up to date. Clone as above for instance seems
> like a good candidate to add. Maybe the tex-source can even be put on
> some website (for personal additions/alterations)?
>
> Best, Jo

Yes, this vignette is behind.

If you want to edit it, you can grab it from r-forge :

$ svn checkout svn://svn.r-forge.r-project.org/svnroot/rcpp
$ cd rcpp/pkg/Rcpp/inst/doc/Rcpp-quickref
$ vi Rcpp-quickref.Rnw
... (write whaterevr edits)
$ cd ..
$ make Rcpp-quickref.pdf
$ svn diff > /tmp/mypatch.diff

and then you send us the mypatch.diff file. We will be happy to look at 
it and integrate it (perhaps with changes).

Romain

-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30
http://romainfrancois.blog.free.fr
|- http://bit.ly/cCmbgg : Rcpp 0.8.6
|- http://bit.ly/bzoWrs : Rcpp svn revision 2000
`- http://bit.ly/b8VNE2 : Rcpp at LondonR, oct 5th




More information about the Rcpp-devel mailing list