I have a function written in RcppArmadillo style and I want to use it for changing variables in the calling environment. I know it is not advisable to do things like this, b
A double
is not a native R type (so there is always a copy being made) and no pass-through reference is possible.
Instead, use Rcpp::NumericVector
which is a proxy for a SEXP
type. This works:
R> sourceCpp("/tmp/so44047145.cpp")
R> x = 1.0
R> myfun(x)
Inside myfun: x = 0.0361444
R> x
[1] 0.0361444
R>
Below is the full code with another small repair or two:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
//[[Rcpp::export]]
void myfun(Rcpp::NumericVector &x){
arma::mat X = arma::randu<arma::mat>(5,5);
arma::mat Y = X.t()*X;
arma::mat R1 = chol(Y);
x[0] = arma::det(R1);
Rcpp::Rcout << "Inside myfun: x = " << x << std::endl;
}
/*** R
x = 1.0 // initialize x
myfun(x) // update x to a new value calculated internally
x // return the new x; it should be different from 1
*/