2014-01-21 17 views
2

讓我們先來生成列表裏面的一些列表:RCPP:使用列表,其中包括列表處理

lappend <- function(lst, ...){ 
    lst <- c(lst, list(...)) 
    return(lst) 
} 

scalarList <- list() 
vectorList <- list() 
MatrixList <- list() 

for (i in 1:3){ 
    scalarList <- lappend(scalarList,i) 
    vectorList <- lappend(vectorList,0:i) 
    MatrixList <- lappend(MatrixList, diag(i + 1)) 
} 

myRList <- list(scalarList = scalarList, vectorList = vectorList, 
    MatrixList = MatrixList) 

現在,我們的myRList準備好了,我想如下寫在C++函數:

1)輸入:1)myRList,2)1到3的ID

2)輸出:該函數應該分別打印對應於輸入ID的標量,矢量和矩陣。

3)寫這個函數可能有很多種方法。我特別想要讀入列表中,並將其分配給相應的arma對象,然後將其打印出來。原因是我寫了這個簡單的例子來向你們學習如何從Rcpp的另一個列表中提取列表的元素並將它分配給一個arma對象。

這裏是我的C++代碼:

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

// [[Rcpp::export]] 
double myListExtractor(Rcpp::List aList_In_R, int id){ 
int myScalar = Rcpp::as<double>(aList_In_R["scalarList"][id]); //? what to do ? 
arma::vec myVector = Rcpp::as<arma::vec>(aList_In_R["vectorList"[id]]); //??? 
arma::mat myMatrix = Rcpp::as<arma::mat>(aList_In_R["MatrixList"[id]]); //??? 

// If I manage to do the three assignments above, then printing is easy: 

Rcpp::Rcout << "myScalar = " << myScalar << std::endl; 
Rcpp::Rcout << "myVector = " << myVector << std::endl; 
Rcpp::Rcout << "myMatrix = " << myMatrix << std::endl; 

return 1; // we don't care about the return for now 
} 

同樣,我100%同意,沒有必要爲它們分配到ARMA對象,然後打印。在我自己的代碼中,我使用arma對象做了很多代數,這就是我強調這項任務以瞭解如何修復代碼的原因/

非常感謝您的幫助。此外,我花了3個小時瀏覽網絡,我沒有找到任何答案。

+0

一種解決方案是調用每個子列表上的函數,或者調用myRList上的函數,我們可以提供具有三個參數myRList的函數$ scalarList ,myRList $ vectorList和myRList $ MatrixList並分別與每個工作 – Sam

+0

搜索'[rcpp] List'有183個結果。你先搜索了嗎? –

+0

@DirkEddelbuettel,早上好。是的,我做到了。正如您在書中所解釋的,從List中檢索元素有很多有用的答案。在處理包含子列表的列表時,我沒有發現任何問題/答案。 – Sam

回答

4

因爲List對象不知道它們包含的對象的類型,所以在每個子集級別都必須有as。例如:

int myScalar = Rcpp::as<double>(Rcpp::as<Rcpp::List>(aList_In_R["scalarList"])[id]); 

這種方式,我們可以通知編譯器,我們正在從aList_In_R提取插槽是List,而我們有List S中的方法應該適用於此。這很醜陋,但使用靜態類型語言來操作動態類型語言中使用的對象是一個不幸的後果。

將模板列表容器放入Rcpp可能有助於解決這種情況;例如而不是有一個List你可能有一個ListOf<List>,其中子集運算符'知道'它應該在子集化後返回List,這可能會更好一點。也許它可以深到ListOf< ListOf<double> >等...

+0

嗨@KevinUshey,完美答案。我的問題現在完全解決了。非常感謝。 – Sam