This question already has answers here:
How do I create a list of vectors in Rcpp?

(2个答案)


4年前关闭。




这可能是一个非常基本的请求,但是我在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变成wout。如何提取多个对象(在这种情况下为eout和wout)?我确实在Dirk的Rcpp简介页中看到了有关list(ret)的内容,但是当我尝试这样做时,我的代码无法编译。任何帮助将不胜感激?

最佳答案

如何删除两个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)

07-24 09:52