【问题标题】:removing sublists from a list从列表中删除子列表
【发布时间】:2017-10-05 12:59:08
【问题描述】:

我有 155 个元素的列表,eahc 包含 3 个列表。

下面我做了一个小例子。我只对保留gene 中的值感兴趣,并尝试在R 中一次删除每个元素的第一个和第二个列表!只留下基因中的值。

test <- list(name="Adipose", desc= "Roche", gene = c("KRT14", "RPE65"))
test1 <- list(name="muscle", desc= "Roche", gene = c("THRSP", "KRT14"))
test2 <- list(name="WBC" , desc= "Roche", gene = c("RBP4", "CCDC80"))
x <- c(test,test1, test2)

如何实现?

【问题讨论】:

  • x[grepl("gene",names(x))]?你不能简单地做x["gene"],因为它只会拉第一个。如果你能澄清你的数据结构会更有帮助。根据您的描述,在我看来 x 是一个列表列表,但在您的输出中 x 只是一个列表
  • @MikeH。不需要whichgreplx[names(x) == 'gene'] 就可以了。
  • 如果总是按顺序,x[c(FALSE, FALSE, TRUE)]
  • @MikeH。如果要匹配gene 1:1,则不需要grepl
  • @MikeH 解决方案有效!但是它在我的数据中是不可重现的,因为真实列表的结构不同,我现在不知道如何制作它。就像str(list) List of 155 $ Adipose :List of 3 ..$ name : chr "Adipose" ..$ desc : chr "Roche" ..$ genes: chr [1:82] "ACACB" "ACP5" "ACTA1" "ADRB3" ... $ WBC :List of 3 ..$ name : chr "WBC" ..$ desc : chr "Roche" ..$ genes: chr [1:28] "THRSP" "KRT14" "APOB" "LEP" ... 我写了这个for ( i in list[[1:155]]) as.list(name=list[[i]][1], gene=list[[i]][3] ) 没用!

标签: r list for-loop subset


【解决方案1】:

如您在 cmets 中发布的dput 所示,您的实际数据结构是列表的列表。在这种情况下,您可以使用lapply 来获得您想要的:

list <- structure(list(Adipose = structure(list(name = "Adipose", desc = "Roche", genes = c("ACACB", "ACP5", "ACTA1")), .Names = c("name", "desc", "genes")), WBC = structure(list( name = "WBC ", desc = "Roche", genes = c("THRSP", "KRT14", "APOB", "LEP")), .Names = c("name", "desc", "genes"))), .Names = c("Adipose ", "WBC "))

lapply(list, function(x) x[names(x)=="genes"])

#$`Adipose `
#$`Adipose `$genes
#[1] "ACACB" "ACP5"  "ACTA1"    
#
#$`WBC `
#$`WBC `$genes
#[1] "THRSP" "KRT14" "APOB"  "LEP"  

【讨论】:

  • 非常感谢,它工作正常。在我提出另一个问题之前,您知道在list 中的每个$genes 中找到相交的方法吗?
  • 您想要列表中所有元素的交集吗?
  • 一次性只列出$genes列表中的元素,例如Adipose$genes, WBC$genes
  • 这可能对stackoverflow.com/questions/3695677/… 有所帮助。尝试在第一个答案中使用Reduce 解决方案。如果不是,我建议发布一个新问题。
猜你喜欢
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-20
  • 2020-10-06
  • 2018-09-26
相关资源
最近更新 更多