2012-01-13 62 views
2

我寫的R包的載體,並希望創建列表的vecor: 我做如下:C到R:創建列表

int dim = 5; 
SEXP root; 
PROTECT(root=allocVector(VECSXP,dim)); 
for(int i=0;i<dim;i++) 
{ 
    SEXP(coerceVector(root))[i] = list1(allocVector(REALSXP, 1)); 
} 
// every list will be appended after 
//I have not any means to know its length in advanc 

不幸的是,這段代碼甚至不進行編譯。 有什麼幫助嗎?

回答

2

假設你的意思是成對列表而不是列表正確的代碼看起來更像

int dim = 5; 
SEXP root = PROTECT(allocVector(VECSXP, dim)); 
for (int i = 0; i < dim; i++) 
    SET_VECTOR_ELT(root, i, list1(allocVector(REALSXP, 1))); 

我不知道這是您的本意,但等同於:

> root = list(pairlist(NA_real_), pairlist(NA_real_), pairlist(NA_real_), pairlist(NA_real_), pairlist(NA_real_)) 
> str(root) 
List of 5 
$ :Dotted pair list of 1 
    ..$ : num NA 
$ :Dotted pair list of 1 
    ..$ : num NA 
$ :Dotted pair list of 1 
    ..$ : num NA 
$ :Dotted pair list of 1 
    ..$ : num NA 
$ :Dotted pair list of 1 
    ..$ : num NA 
+0

非常感謝。這正是我想要的。但是,訪問配對列表對我來說仍然是個問題。我想要例如訪問列表向量中第三個列表的第一個元素。我嘗試:CAR(根[2]),但它不起作用。通過類比你的代碼,我嘗試了CAR(GET_VECTOR_ELT(root,2)),但它不起作用:GET_VECTOR_ELT沒有定義。 – 2012-01-14 11:23:38

+0

請考慮閱讀R-exts - 它確實有幫助;)。你正在尋找的是'VECTOR_ELT' – 2012-01-14 11:35:47

+0

非常感謝..即使我看着寫R-exts,我也無法自己找到它(在做出迴應之後,我搜索了VECTOR_ELT,但沒有找到它)。您爲我節省了大量時間和精力,再次感謝 – 2012-01-14 11:55:21