23

我是 R 的新手。我 t1在 R 中有一个列表,看起来像

[[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。我怎样才能做到这一点?

4

7 回答 7

21

rapply提供另一种选择:

unique(rapply(t1, function(x) head(x, 1)))
于 2013-01-17T12:08:50.930 回答
19

另一种方法是使用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"
于 2013-01-17T10:09:51.420 回答
14

我会使用do.callandrbind将列表连接成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"
于 2013-01-17T10:07:52.220 回答
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"   
于 2013-01-17T10:29:18.893 回答
4

使用包rlist,即

library(rlist)
yourlist %>>% list.map(.[1])
于 2017-11-16T17:25:58.247 回答
1

作为 2020 年的更新,使用purrr. 使用@Gago-Silva 的测试列表:

library(purrr)
t1 %>% flatten() %>% map(1) %>% as_vector()

子列表被展平为字符向量,从中提取元素 1,并将此单元素字符向量列表转换为一个向量。

另请注意,您可以直接从列表列表中获取一个小标题

t1 %>% flatten_dfc()
于 2020-05-01T23:44:18.493 回答
1

使用基础 R:

t1 <- list(list("a", "control"), list("a", "disease"), list("b", "control"))
id <- sapply(t1, function(x) {x[[1]]})
unique(id)
于 2022-01-06T16:53:02.077 回答