[Rcpp-devel] Initializing Armadillo vec/cube from NumericVector using as conversion

Helske, Jouni jouni.helske at jyu.fi
Thu Sep 22 21:39:45 CEST 2016


Hi,

I was recently hunting down a bug in my code, and stumbled upon a slightly incoherent behaviour in Rcpp/RcppArmadillo. In my real application I have a class which data members are initialized in initialization list from the Rcpp List using as<arma::cube>. For example, I have a member y which I initialize by y(as<arma::cube>(xlist["y"])). This caused some headaches if I later modified data member y, as the y in the list on R side was modified as well. I then realized that I need to use Rcpp::clone in order to make a deep copy of xlist object. But, this does not need to be done when initializing arma::vec or arma::mat. Is this purposeful or am I missing something?

Simple example:

void test1(const NumericVector& x) {
  arma::cube ycube(as<arma::cube>(x));
  ycube(0) = 0.5;
}

> y <- array(1:4, c(2,2,1)) #y is integer type, using automatic copy
> test1(y)
> y
, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

> y <- array(as.numeric(1:4), c(2,2,1)) #y is numeric, no copy
> test1(y)
> y
, , 1

     [,1] [,2]
[1,]  0.5    3
[2,]  2.0    4


But in case of arma::vec (or arma::mat), copying is always done:

void test2(const NumericVector& x) {
  arma::vec yvec(as<arma::vec>(x));
  yvec(0) = 0.5;
}

> y <- as.numeric(1:8)
> test2(y)
> y
[1] 1 2 3 4 5 6 7 8

Best regards,

Jouni Helske

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20160922/53a99668/attachment.html>


More information about the Rcpp-devel mailing list