这可能是一个非常基本的请求,但我在R中有一个Rcpp函数来计算我想要传递给R的各种矩阵。我的代码看起来像这样:
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)
我希望将'eout'和'wout'传递回R,但显然只返回最后返回的值(即wout)。所以d变得枯萎了。如何提取多个对象(在这种情况下是eout和wout)?我确实在Dirk的Rcpp介绍表中看到了它有关于list(ret)的东西但是当我尝试这个时我的代码不能编译。任何帮助都会非常感激吗?
答案 0 :(得分:4)
如何删除return
个语句并添加:
List ret;
ret["eout"] = eout;
ret["wout"] = wout;
return ret;`
并将eastC
的返回类型更改为List
。
所以,结果应该是:
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)