【问题标题】:Any way to extract out named IntegerList more elegantly from nested list?有什么方法可以从嵌套列表中更优雅地提取命名 IntegerList 吗?
【发布时间】:2016-10-01 15:00:08
【问题描述】:

我在 IntegerList 中有位置索引列表,我打算在给定阈值的情况下过滤它们,并且效果很好。但是,我想为每个 IntegerList 提取一个特定的过滤集以供进一步使用。我知道 myList 是嵌套列表,并且数据非常基于真实数据集进行模拟。有什么方法可以轻松优雅地检索想要的 IntegerList 吗?我怎样才能使它发生这种提取?

要运行迷你示例,需要以下库:

library(IRanges)
library(S4Vectors)

小例子:

myList <- list(f1=IntegerList(1,2,3,4,1,1,1,integer(0),1,2,4),
               f2=IntegerList(1,5,integer(0),integer(0),2,3,4,6,1,5,6),
               f3=IntegerList(1,4,6,7,2,3,3,7,2,5,7))

len <- Reduce('+', lapply(myList, lengths))
keepMe <- len >= length(myList)

我打算将它们过滤如下:

res.filt <- lapply(myList, function(elm) {
  ans <- list(keep=elm[keepMe], droped=elm[!keepMe])
  ans
})

我的粗略输出:

Keep.list <- list(f1.kp=res.filt$f1$keep, f2.kp=res.filt$f2$keep, f3.kp=res.filt$f3$keep)
Drop.list <- list(f1.dp=res.filt$f1$droped, f2.dp=res.filt$f2$droped, f3.dp=res.filt$f3$droped)

根据我粗略的输出,我怎样才能得到更优雅的输出?任何有效的方法来实现我的输出?谁能指出我该怎么做?或任何建议如何获得我的预期输出?提前致谢

【问题讨论】:

  • 您能准确解释一下您所说的“更优雅”是什么意思吗?
  • 我只是不明白你说的是结果、代码还是输出的格式
  • 感谢您的快速回复。我得到了解决方案:)

标签: r list extraction iranges


【解决方案1】:

您过滤向量列表的思维过程/流程是合乎逻辑且非常理想的,但如果您使用purrr,则可以稍微收紧一点:

library(purrr)

map(myList, lengths) %>% 
  reduce(`+`) %>% 
  map_lgl(`>=`, length(myList)) -> keep_me

keep_list <- map(myList, ~.[keep_me])
drop_list <- map(myList, ~.[!keep_me])

【讨论】:

  • 这是一个很棒的解决方案。我感谢 purrr 软件包的开发者。非常感谢:)
  • 不客气!虽然这实际上只是在做你正在做的事情。代码稍微紧凑一点。你有一个很好的、有效的解决方案。
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
相关资源
最近更新 更多