2013-01-17 24 views
18

我是一個新手,以R.我在R A名單t1看起來像從列出的清單,如何提取元素

[[1]] 
[[1]][[1]] 
[1] "a"  "control" 


[[2]] 
[[2]][[1]] 
[1] "a"  "disease1" 


[[3]] 
[[3]][[1]] 
[1] "a"  "disease2" 


[[4]] 
[[4]][[1]] 
[1] "b"  "control" 


[[5]] 
[[5]][[1]] 
[1] "b"  "disease1" 


[[6]] 
[[6]][[1]] 
[1] "b"  "disease2" 

我需要得到第一要素的唯一列表爲載體即[ 「a」,「b」]從這個向量t1。我怎樣才能做到這一點?

+2

請提供一個可重現的例子,例如使用'dput'。 –

回答

16

rapply提供了另一種選擇:

unique(rapply(t1, function(x) head(x, 1))) 
+0

可愛簡潔。我喜歡。 –

+0

謝謝馬特,確實非常簡潔! – rlpatrao

+1

FWIW,您可以使用'tail()'而不是'head()'來獲取每個最終元素,而不是第一個元素。 – user1092247

13

我會使用do.callrbind將列表連接成data.frame。然後你可以使用unique第一列以獲得獨特的項目(使用@AR給出的例子):

spam = do.call("rbind", lapply(t1, "[[", 1)) 
> spam 
    [,1] [,2]  
[1,] "a" "control"               
[2,] "b" "disease1" 
> unique(spam[,1]) 
[1] "a" "b" 
+0

這很好,我很快就開始使用* apply函數,並且一直忽略它們。 –

+0

apply函數真的可以和數組類型或列表數據一起工作,而且很多人開始使用R會覺得不舒服。我真的會建議嘗試將它們添加到你的武庫,它可以產生非常有效和短的解決方案。 –

+0

謝謝,這是一個很好的答案。 –

16

另一種方法是使用unlist

> t1=list(list(c("a","control")),list(c("b","disease1"))) 
> t1 
[[1]] 
[[1]][[1]] 
[1] "a"  "control" 


[[2]] 
[[2]][[1]] 
[1] "b"  "disease1" 

> matrix(unlist(t1),ncol=2,byrow=TRUE) 
    [,1] [,2]  
[1,] "a" "control" 
[2,] "b" "disease1" 
+0

+1使用unlist,我認爲這取決於多層列表的確切形狀比我的解決方案。 –

+0

是的,它有這樣的限制:) @rlpatrao給出的例子並沒有提到任何有關這方面的內容,但你是對的。 –

+0

非常感謝,實際上這對我很好。我有相同數量的列。我也喜歡@Matthew Plourde的回答,因爲它非常簡潔! – rlpatrao

4

我試圖治療一個或多個子列表包含多個元素的一般情況。

例如:

ll <- 
     list(list(c("a","control")), 
      list(c("b","disease1")), 
      list(c("c","disease2"),c("c","disease2bis")), # 2 elements 
      list(c("d","disease3")), 
      list(c("e","disease4")) 
) 

你可以做這樣的事情:

unlist(lapply(ll,         ## for each element in the big list 
     function(x) 
      sapply(1:length(x),     ## for each element in the sublist 
      function(y)do.call("[[",list(x,y))))) ## retrieve x[[y]] 


[1] "a"   "control"  "b"   "disease1" "c"   
    "disease2" "c"   "disease2bis" "d"   "disease3" 
[11] "e"   "disease4" 
1

使用包rlist,即

library(rlist) 
yourlist %>>% list.map(.[1])