2017-05-18 8 views
2

Ich habe eine Funktion in RcppArmadillo Stil geschrieben und ich möchte es für das Ändern von Variablen in der aufrufenden Umgebung verwenden. Ich weiß, es ist nicht ratsam, solche Dinge zu tun, aber es ist in meinem Fall hilfreich. Konkret versuche ich das:Funktion übergeben durch Verweis in RcppArmadillo

#include <RcppArmadillo.h> 
#include <iostream> 

//[[Rcpp::export]] 
void myfun(double &x){ 
    arma::mat X = arma::randu<arma::mat>(5,5); 
    arma::mat Y = X.t()*X; 
    arma::mat R1 = chol(Y); 

    x = arma::det(R1); 
    std::cout << "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 
*/ 

Was vermisse ich? Warum funktioniert nicht?

Antwort

3

Ein double ist kein nativer R-Typ (so wird immer eine Kopie erstellt) und keine Pass-Through-Referenz ist möglich.

Verwenden Sie stattdessen Rcpp::NumericVector, die ein Proxy für einen Typ ist. Dies funktioniert:

R> sourceCpp("/tmp/so44047145.cpp") 

R> x = 1.0 

R> myfun(x) 
Inside myfun: x = 0.0361444 

R> x   
[1] 0.0361444 
R> 

Unterhalb der vollständige Code mit einer anderen kleinen Reparatur oder zwei:

#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 
*/ 
Verwandte Themen