[英]Rcpp: Dealing with Lists that include Lists
讓我們首先生成一些包含列表的列表:
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個小時瀏覽網絡,我沒有找到任何答案。
由於List
對象不知道它們包含,您必須對象的類型,任何as
在子集的每個級別。 例如:
int myScalar = Rcpp::as<double>( Rcpp::as<Rcpp::List>(aList_In_R["scalarList"])[id] );
這樣,我們可以向編譯器發出信號,我們從aList_In_R
提取的插槽是List
,而我們為List
的所有方法都應該適用於此處。 這很丑陋,但使用靜態類型語言操作動態類型語言中使用的對象是一個不幸的結果。
將模板化列表容器放入Rcpp
可能有助於解決這種情況; 例如,代替擁有List
你可能有一個ListOf< List >
,子集運算符將“知道”它應該在子集化后返回List
,這可能會更好一些。 也許它可以像ListOf< ListOf< double > >
那樣深入......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.