2015-06-30 28 views
1

我確定Rcpp中的List對象的一些操作,比如獲取元素的數量和引用第i個元素等等......代碼如下,其中X是具有相同行數的矩陣的Listrcpp中「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); 

但顯然東西是錯誤的。

+0

我對你的問題是否與(1)加入'arma :: mat'有一個'Rcpp :: List'的元素有點困惑,因爲你的標題表示;或者(2)找到(?)/(?)一個'Rcpp :: List'的長度的元素數,如下面的答案中所述。你能澄清一下嗎? – nrussell

+0

我的X是一個由矩陣組成的列表,我想知道X中有多少個矩陣(即列表中有多少個元素)。謝謝! –

回答

0

我假設你的最終目標是與所有的矩陣概括的Y的加盟X,所以這就是我走近以下問題:

#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與使用輸入的列更新。

此仿函數被用在該輔助功能accum_join,這需要合適的輸入對象,並通過使用std::for_each算法(注後.x - for_each本身不具有一個返回值)返回累積arma::mat

最後一個函數只是返回你的問題顯示的樣式列表,除了第三個元素是現在的Y串聯和所有X的元素,而不是YX第一要素。


相比於原來的功能 -

// [[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 

而只是爲了澄清關於您的其他問題,

int K = X.n_elem; //我試圖讓X

的elems的的#你想X.size()(該Rcpp::方法),而不是X.n_elem(該arma::方法)。

+1

是的,那正是我想要的。謝謝! –

0

我只是想出了:

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

是正確的,但我還是不知道如何讓一個「列表」對象elems的的#。我想這應該是非常基本的...