我如何 return 从 Rcpp 到 R 的矩阵列表?

How can I return a list of matrices from Rcpp to R?

我在 Rcpp 中有一个函数做这样的事情:它创建一个 std::list 类型的矩阵列表,并打算 return 将该矩阵列表返回给 R。

我在这里附上一个简化的例子:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
Rcpp::List splitImagesRcpp(arma::mat x) 
{
   std::list<arma::mat> listOfRelevantImages;
   int relevantSampleSize = x.n_rows;
   for(int k = 0; k < relevantSampleSize; ++k)
   {
      listOfRelevantImages.push_back(x.row(k));
   }
   return wrap(listOfRelevantImages);
}

这里的问题是,我想return R 一个矩阵列表,但我得到一个向量列表。我一直在尝试很多并查看文档,但我似乎无法找到解决方案。看起来 wrap 正在完成它的工作,但它也在列表中递归地包装我的矩阵。

我得到这样的结果:

> str(testingMatrix)
List of 200
 $ : num [1:400] 1 1 1 1 1 1 1 1 1 1 ...
 $ : num [1:400] 1 1 1 1 1 1 1 1 1 1 ...

但我想得到这样的东西:

> str(testingMatrix)
List of 200
 $ : num [1:40, 1:10] 1 1 1 1 1 1 1 1 1 1 ...
 $ : num [1:40, 1:10] 1 1 1 1 1 1 1 1 1 1 ...

我想在 Rcpp 中而不是在 R 中执行此操作。那是因为我希望能够将函数与纯 R 编程的函数互换,以便测量加速比。[​​=14=]

非常感谢任何帮助!

使用 arma::field class that has the necessary plumbing to convert to and fro RC++.

这里有一些示例代码,说明如何使用字段 class,因为上面的示例不可重现...

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]

// [[Rcpp::export]]
arma::field<arma::mat> splitImagesRcpp(arma::mat x) {

    // Sample size
    int relevantSampleSize = x.n_rows;

    // Create a field class with a pre-set amount of elements
    arma::field<arma::mat> listOfRelevantImages(relevantSampleSize);

    for(int k = 0; k < relevantSampleSize; ++k)
    {
        listOfRelevantImages(k) = x.row(k);
    }


    return listOfRelevantImages;
}

示例:

set.seed(1572)
(x = matrix(runif(25), 5, 5))
#           [,1]        [,2]      [,3]      [,4]       [,5]
# [1,] 0.2984725 0.679958392 0.5636401 0.9681282 0.25082559
# [2,] 0.3657812 0.157172256 0.6101798 0.5743112 0.62983179
# [3,] 0.6079879 0.419813382 0.5165553 0.3922179 0.64542093
# [4,] 0.4080833 0.888144280 0.5891880 0.6170115 0.13076836
# [5,] 0.8992992 0.002045309 0.3876262 0.9850514 0.03276458
(y = splitImagesRcpp(x))
#      [,1]     
# [1,] Numeric,5
# [2,] Numeric,5
# [3,] Numeric,5
# [4,] Numeric,5
# [5,] Numeric,5
y[[1]]
#           [,1]      [,2]      [,3]      [,4]      [,5]
# [1,] 0.2984725 0.6799584 0.5636401 0.9681282 0.2508256