在rcpp中操作“List”对象

时间:2015-06-30 16:59:00

标签: r list rcpp

我确定Rcpp中List个对象的一些操作,比如获取元素的数量和引用第i个元素等等......代码如下,X这里是具有相同行数的List矩阵。

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

#include <Rcpp.h>
using namespace arma;
using namespace Rcpp;
using namespace std;
using namespace sugar;

// [[Rcpp::export]]
List Test_C(mat Y, List X){       
  int K = X.n_elem; //I was trying to get the # of elems of X
  mat X1 = X[1];    //I was trying to get the first matrix in X
  mat YX1 = [Y, X1]; //I was trying to combine Y and X1 to one matrix.
  List out;
  out["K"] = K;
  out["X1"] = X1;
  out["YX1"] = YX1;
  return(out);
}

我使用此代码并在R中调用它:{YX在R中定义良好

Test_C(Y, X);

但显然有些不对劲。

2 个答案:

答案 0 :(得分:0)

我刚想通了:

mat X1 = X[0];  
mat YX1 = join_rows(Y, X1);

是正确的,但我仍然不知道如何获得“List”对象的元素数量。我认为这应该是非常基本的......

答案 1 :(得分:0)

我假设你的最终目标是推广YX中所有矩阵的加入,这就是我如何处理下面的问题:

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

struct fill_from_list {
  fill_from_list(const arma::mat& init)
    : x(init) {}
  void operator()(const arma::mat& m) {
    x = arma::join_rows(x, m);
  }
  arma::mat x;
};

arma::mat accum_join(const arma::mat& init, Rcpp::List X) {
  return std::for_each(X.begin(), X.end(), fill_from_list(init)).x;
}

// [[Rcpp::export]]
Rcpp::List Test_C2(const arma::mat& Y, Rcpp::List X) {
  return Rcpp::List::create(
    Rcpp::Named("K") = X.size(),
    Rcpp::Named("X1") = X[0],
    Rcpp::Named("YXK") = accum_join(Y, X));
}

为了详细说明,函数对象fill_from_list由初始arma::mat构成,每次通过arma::mat向其传递一个operator()时,数据成员x使用arma::join_rows更新输入列。

这个仿函数在辅助函数accum_join中使用,它使用适当的输入对象并使用arma::mat算法返回累积的std::for_each注意尾随{{} 1}} - .x本身没有返回值)。

最后一个函数只返回问题中显示的样式列表,但第三个元素现在是for_each和所有Y元素的串联,而不是{{1 }和X的第一个元素。

与原始功能相比 -

Y

我们有:

X

只是为了澄清你的另一个问题,

  

int K = X.n_elem; //我试图获得X的元素数

您需要// [[Rcpp::export]] Rcpp::List Test_C(arma::mat Y, Rcpp::List X){ int K = X.size(); arma::mat X1 = X[0]; arma::mat YX1 = arma::join_rows(Y, X1); Rcpp::List out; out["K"] = K; out["X1"] = X1; out["YXK"] = YX1; return out; } mlist <- lapply(1:4, function(x) matrix(x, nrow = 3, ncol = x)) > all.equal(Test_C(mlist[[1]], mlist[2]), Test_C2(mlist[[1]], mlist[2])) [1] TRUE ## including matrices 3 and 4: > Test_C2(mlist[[1]], mlist[2:4]) $K [1] 3 $X1 [,1] [,2] [1,] 2 2 [2,] 2 2 [3,] 2 2 $YXK [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 2 2 3 3 3 4 4 4 4 [2,] 1 2 2 3 3 3 4 4 4 4 [3,] 1 2 2 3 3 3 4 4 4 4 方法),而不是X.size()Rcpp::方法)。