R 如何从列表列表中提取元素

R 如何从列表列表中提取元素,r,vector,R,Vector,我是R的新手。我在R中有一个列表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]]

我是R的新手。我在R中有一个列表
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"

我需要从这个向量
t1
中得到一个向量中第一个元素的唯一列表,即[“a”,“b”]。我该怎么做

我会使用
do.call
rbind
将列表连接到
data.frame
中。然后,您可以在第一列上使用
unique
,以获取唯一的项目(使用@A.R.给出的示例):


另一种方法是使用
取消列表

> 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"

我试图处理一个或多个子列表包含多个元素的一般情况

例如:

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"))
)

rappy
提供了另一种选择:

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

使用软件包
rlist
,即

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

作为2020年的一项更新,使用
purr
可以轻松直观地完成这项工作。使用@Gago Silva的测试列表:

library(purrr)
t1 %>% flatten() %>% map(1) %>% as_vector()
子列表被展平为字符向量,元素1从中提取,一个元素的字符向量列表转换为一个向量

还请注意,您可以直接从列表列表中使用

t1 %>% flatten_dfc()

请提供一个可复制的示例,例如,使用
dput
+1来使用unlist,我认为它比我的解决方案更依赖于多层列表的确切形状。是的,它有局限性:)@rlpatrao给出的示例没有说明这一点,但你是对的。非常感谢各位,实际上这对我来说很有效。我有相同数量的列。我也喜欢@Matthew Plourde的答案,因为它非常简洁!这很好,我不久前开始使用*apply函数,但我一直忽略它们。apply函数实际上与数组类型或列表数据一起工作,很多开始使用R的人觉得不舒服。我真的建议你尝试将它们加入你的兵工厂,它可以产生非常有效和简短的解决方案。谢谢,这是一个伟大的答案。可爱和简洁。我喜欢。谢谢马特,非常简洁!FWIW,您可以使用
tail()
而不是
head()
来获取每个最终元素,而不是第一个元素。
library(purrr)
t1 %>% flatten() %>% map(1) %>% as_vector()
t1 %>% flatten_dfc()