2014-01-28 53 views
1

讓我們假設我有以下結構:如何獲取和設置在嵌套列表元素

R-代碼

listAll = list() 
list3 = list(id=14,attr1 = '',attr2='n4',attr3=list(text1='tx1',text2='')) 
list4 = list(id=15,attr1 = '',attr2='n1',attr3=list(text1='tx1',text2='')) 
listAll = append(listAll,list(values=list3)) 
listAll = append(listAll,list(values=list4)) 
str(listAll) 

#result 

List of 2 
$ values:List of 4 
..$ id : num 14 
..$ attr1: chr "" 
..$ attr2: chr "n4" 
..$ attr3:List of 2 
.. ..$ text1: chr "tx1" 
.. ..$ text2: chr "" 
$ values:List of 4 
..$ id : num 15 
..$ attr1: chr "" 
..$ attr2: chr "n1" 
..$ attr3:List of 2 
.. ..$ text1: chr "tx1" 
.. ..$ text2: chr "" 

我怎樣才能設置/獲取例如屬於ID attR2位14?

我想這不可能是困難的......所有我需要做的是(對GET):

  1. 獲取指數的搜索ID對應於這個指數
  2. 獲取列表從第二步獲得價值$ attr1的名單

不幸的是我不知道如何讓第一點完成。

認爲我有ID = 14,對應的索引1..the接下來的步驟將是(兩個和三個一起):

listAll[[1]]$attr2 #results "n4" 

所以現在的問題是如何獲得指數(在這個例子中= 1)匹配id = 14. 任何人都可以幫忙嗎?

回答

3

你可以達到你想要使用的是什麼sapply

## sapply(listAll, "[[", "id") 
## werte werte 
## 14 15 

那麼你可以申請which得到這樣

which(sapply(listAll, "[[", "id") == 14) 
## werte 
##  1 

which(sapply(listAll, "[[", "id") == 15) 
## werte 
##  2 
+0

索引非常感謝您! – user3246502