问题
I checked many examples about how to pass by reference using Rcpp. I see for instance this very great. However I have one question. Suppose that I have a matrix as an object in R and I want to add 1 to the entry [1,1]. The examples i saw work if the matrix is in Cpp but i want to return the update in R without using return statement.
This is an example i did with a list and it works very well
//[[Rcpp::export]]
void test(List& a){
a(0)=0;
}
I need to do similarely with a matrix. something like :
//[[Rcpp::export]]
void test(arma::mat& a){
a(0,0)=0;
}
The second does not update my matrix in R but updates the list.
Can anyone help me ?
回答1:
Let's start by reiterating that this is probably bad practice. Don't use void
, return your changed object -- a more common approach.
That said, you can make it work in either way. For RcppArmadillo, pass by (explicit) reference. I get the desired behaviour
> sourceCpp("/tmp/so.cpp")
> M1 <- M2 <- matrix(0, 2, 2)
> bar(M1)
> M1
[,1] [,2]
[1,] 42 0
[2,] 0 0
> foo(M2)
> M2
[,1] [,2]
[1,] 42 0
[2,] 0 0
>
out of this short example:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
void bar(Rcpp::NumericMatrix M) {
M(0,0) = 42;
}
// [[Rcpp::export]]
void foo(arma::mat M) {
M(0,0) = 42;
}
/*** R
M1 <- M2 <- matrix(0, 2, 2)
bar(M1)
M1
foo(M2)
M2
*/
来源:https://stackoverflow.com/questions/46087970/rcpp-update-matrix-passed-by-reference-and-return-the-update-in-r