[Rcpp-devel] Call by reference

Rguy rguy at 123mail.org
Wed Jul 29 08:29:02 CEST 2015


Soren,

Thanks for the insight. For other readers possibly struggling with call by
reference, the following code works as expected, i.e., x is changed to c(1,
2).

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void absC(NumericVector & x) {
int n = x.size();
for (int i = 0; i < n; ++i) {
if (x[i] < 0) x[i] = -x[i];
}
}

/*** R
x = c(-1, -2)
absC(x)
x
*/


On Wed, Jul 29, 2015 at 5:36 AM, Søren Højsgaard <sorenh at math.aau.dk> wrote:

> Just a follow up on "copying": If you copying": If you do
>
> #include <Rcpp.h>
> using namespace Rcpp;
>
> // [[Rcpp::export]]
> void absC(NumericVector & x) {
> if (x[0] < 0)
>   x = -x;
> }
>
> /*** R
> y <- -1L
> absC(y)
> y
> */
>
> you'll get
>
> > y <- -1L
> > absC(y)
> > y
> [1] -1
>
> and that is because an IntegerVector is provided but a NumericVector is
> expected; hence a copying takes place.
>
> Regards
> Søren
>
>
>
>
> |-----Original Message-----
> |From: rcpp-devel-bounces at lists.r-forge.r-project.org [mailto:rcpp-devel-
> |bounces at lists.r-forge.r-project.org] On Behalf Of Dirk Eddelbuettel
> |Sent: 28. juli 2015 20:46
> |To: Rguy
> |Cc: rcpp-devel at lists.r-forge.r-project.org
> |Subject: Re: [Rcpp-devel] Call by reference
> |
> |
> |On 28 July 2015 at 17:53, Rguy wrote:
> || I attempted to implement the call by reference example on page 200 of
> || Seamless R and C++, as follows:
> ||
> || #include <Rcpp.h>
> || using namespace Rcpp;
> ||
> || // [[Rcpp::export]]
> || void absC(double & x) {
> || if (x < 0) x = -x;
> || }
> ||
> || /*** R
> || x = -1
> || absC(x)
> || x
> || */
> ||
> || Unfortunately, x remains equal to -1.
> || Platforms: Windows 7,  "R version 3.1.3 Patched (2015-03-16 r68103)".
> || Please advise.
> |
> |An (atomic) double does not exist in R, so you are _always_ forcing a
> |copy, which works against your intent here.
> |
> |Try replacing double with Rcpp::NumericVector.
> |
> |Dirk
> |
> |
> |--
> |http://dirk.eddelbuettel.com | @eddelbuettel | edd at debian.org
> |_______________________________________________
> |Rcpp-devel mailing list
> |Rcpp-devel at lists.r-forge.r-project.org
> |https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20150729/d3eeb07b/attachment.html>


More information about the Rcpp-devel mailing list