2

This may be a very basic request, but I have a Rcpp function in R that calculates various matrices which I want to pass back to R. My code looks like this:

zeromatrix <- matrix(0,6,1)
east <- matrix(seq(1:48),6,8)
west <- matrix(seq(1:48),6,8)
func <- 'NumericMatrix eastC(NumericMatrix e, NumericMatrix w, NumericMatrix zeromatrix) {
int ecoln=e.ncol();
int ecolnlessone = ecoln - 1;
NumericMatrix eout(e.nrow(),e.ncol()) ;
for (int j = 0;j < ecoln;j++) {
if (j > 0) {
eout(_,j) = e(_,j-1);
} else {
eout(_,j) = e(_,0);
}
}
eout(_,0) = zeromatrix(_,0);
return eout;

NumericMatrix wout(w.nrow(),w.ncol()) ;
for (int j = 0;j < ecoln;j++) {
if (j < ecolnlessone) {
wout(_,j) = w(_,j+1);
} else {
wout(_,j) = w(_,j);
}
}
wout(_,ecolnlessone) = zeromatrix(_,0);
return wout;
}'
cppFunction(func)

d <- eastC(east, west, zeromatrix)

I want both 'eout' and 'wout' to be passed back to R but obviously only the last returned value is passed back (i.e. wout). So d becomes wout. How do I extract multiple objects (i.e. eout and wout in this case)? I did see in Dirk's introduction sheets to Rcpp and it had something about list(ret) but when I tried this my code wouldn't compile. Any help would be hugely appreciated?

AntonyDW
  • 349
  • 5
  • 17
  • See the question I just linked to, You want `Rcpp::List::create()` and assign your object in that call. – Dirk Eddelbuettel Dec 09 '15 at 11:44
  • Thanks. But anything I try with :: in it (such as Rcpp::List::create()) just fails. I am using Revolutionary R. I would love to get the armadillo package working but despite loading the libraries none of your examples work. I'm not sure if it is because I don't have RTools installed properly or not. I need the algebra tools that armadillo offers. The answer below appears to answer my question though. Thanks. – AntonyDW Dec 09 '15 at 12:01

1 Answers1

6

How about removing both return statements and add:

List ret;
ret["eout"] = eout;
ret["wout"] = wout;
return ret;`

And change the return type of eastC to List.

So, the result should be like:

zeromatrix <- matrix(0,6,1)
east <- matrix(seq(1:48),6,8)
west <- matrix(seq(1:48),6,8)
func <- 'List eastC(NumericMatrix e, NumericMatrix w, NumericMatrix zeromatrix) {
int ecoln=e.ncol();
int ecolnlessone = ecoln - 1;
NumericMatrix eout(e.nrow(),e.ncol()) ;
for (int j = 0;j < ecoln;j++) {
if (j > 0) {
eout(_,j) = e(_,j-1);
} else {
eout(_,j) = e(_,0);
}
}
eout(_,0) = zeromatrix(_,0);

NumericMatrix wout(w.nrow(),w.ncol()) ;
for (int j = 0;j < ecoln;j++) {
if (j < ecolnlessone) {
wout(_,j) = w(_,j+1);
} else {
wout(_,j) = w(_,j);
}
}
wout(_,ecolnlessone) = zeromatrix(_,0);
List ret;
ret["eout"] = eout;
ret["wout"] = wout;
return ret;
}'
cppFunction(func)

d <- eastC(east, west, zeromatrix)
Richard
  • 56,349
  • 34
  • 180
  • 251
rinni
  • 2,246
  • 1
  • 18
  • 21