【问题标题】:Select nested sublist of a list based on condition in R根据R中的条件选择列表的嵌套子列表
【发布时间】:2017-11-13 10:00:58
【问题描述】:

我确实有以下嵌套列表的简单示例:

list(list(structure(list(group = "a", def = "control"), .Names =  c("group", 
"def"))), list(structure(list(group = "b", def = "disease1"), .Names = c("group", 
"def"))))

结构如下:

str(t1)
List of 2
$ :List of 1
..$ :List of 2
.. ..$ group: chr "a"
.. ..$ def  : chr "control"
$ :List of 1
..$ :List of 2
.. ..$ group: chr "b"
.. ..$ def  : chr "disease1"

有没有一种简单的方法可以只获取满足特定条件的嵌套列表。例如,如果我只知道组的名称,例如“a”,我将如何获得相应的子列表;在示例中,这将是第一个嵌套列表:

[[1]]
[[1]]$group
[1] "a"

[[1]]$def
[1] "control"

所以本质上我正在寻找一种在这个嵌套列表结构中应用group == "a" 的方法。

【问题讨论】:

    标签: r list filter


    【解决方案1】:

    我们可以使用lapply 提取列表的子列表。我们也可以写一个函数。

    get_sublist <- function(group_name) {
       lst[lapply(lst, function(x) x[[1]][[1]]) == group_name]
    }
    
    
    get_sublist("a")
    #[[1]]
    #[[1]][[1]]
    #[[1]][[1]]$group
    #[1] "a"
    
    #[[1]][[1]]$def
    #[1] "control"
    
    get_sublist("b")
    #[[1]]
    #[[1]][[1]]
    #[[1]][[1]]$group
    #[1] "b"
    
    #[[1]][[1]]$def
    #[1] "disease1"
    

    【讨论】:

      【解决方案2】:

      我们可以转换为tibble,然后使用map 创建一个逻辑向量来子集“lst”

      library(purrr)
      library(magrittr)
      library(tibble)
      lst %>% 
            map_lgl(., ~map_lgl(., ~as.tibble(.) %>%
            .$group=='a')) %>%
             extract(lst, .) %>%
             .[[1]]
      #[[1]]
      #[[1]]$group
      #[1] "a"
      
      #[[1]]$def
      #[1] "control"
      

      或使用modify_depth

      lst %>% 
           modify_depth(., 2, ~as.tibble(.)[['group']]=='a') %>%
           unlist %>%
           extract(lst, .)
      

      这里,我们假设'group' 的位置可以在list 中改变。

      【讨论】:

        【解决方案3】:

        除了已经提供的答案之外,我还设法使用“purrr”库中的“keep”获得了正确的结果:

        library(purrr)
        get_sublist <- function(group_name) {
        keep(l, function(x) x[[1]][[1]] == group_name)
        }
        get_sublist("b")
        

        【讨论】:

          猜你喜欢
          • 2022-01-18
          • 2021-08-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-15
          • 1970-01-01
          • 2020-09-09
          • 2016-07-30
          • 1970-01-01
          相关资源
          最近更新 更多