讓我們先來生成列表裏面的一些列表: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個小時瀏覽網絡,我沒有找到任何答案。
一種解決方案是調用每個子列表上的函數,或者調用myRList上的函數,我們可以提供具有三個參數myRList的函數$ scalarList ,myRList $ vectorList和myRList $ MatrixList並分別與每個工作 – Sam
搜索'[rcpp] List'有183個結果。你先搜索了嗎? –
@DirkEddelbuettel,早上好。是的,我做到了。正如您在書中所解釋的,從List中檢索元素有很多有用的答案。在處理包含子列表的列表時,我沒有發現任何問題/答案。 – Sam