【问题标题】:Nested list to dataframe [using purrr + map]嵌套列表到数据框 [使用 purrr + map]
【发布时间】:2020-01-25 01:47:55
【问题描述】:

我查看了很多帖子,如果这是多余的,我很抱歉,但希望能在扁平化嵌套列表方面获得一些帮助:

test <- list()
test <- c(
  list("A" = c(list("1"), list("2"), list("3"))), 
  list("B" = c(list("4"), list("5"), list("6")))
)

期望的输出

  name subcat
1    A      1
2    A      2
3    A      3
4    B      4
5    B      5
6    B      6

我正在努力编写一个嵌套的 for 循环,但我真的很想使用 purrr 或更优雅的东西来创建一个包含两列的数据框:subcat 列和一个重复列,用于在列表。

任何帮助表示赞赏,即使只是将我指向类似的帖子 - 谢谢!

【问题讨论】:

    标签: r list nested purrr


    【解决方案1】:

    你可以试试:

    library(purrr)  
    
    test1 <- flatten(test)
    do.call(rbind.data.frame, map2(map_chr(test1, `[[`, 'name'), 
                                   map(test1, `[[`, 'subcat'), cbind))
    
    #  V1 V2
    #1  A  1
    #2  A  2
    #3  A  3
    #4  B  4
    #5  B  5
    #6  B  6
    

    对于更新的数据:

    library(tidyverse)
    enframe(test) %>%  unnest_longer(value)
    
    # A tibble: 6 x 2
    #  name  value
    #  <chr> <chr>
    #1 A     1    
    #2 A     2    
    #3 A     3    
    #4 B     4    
    #5 B     5    
    #6 B     6   
    

    【讨论】:

    • 非常感谢您的帮助!我将上面的示例更改为更能代表我的数据。你介意看看吗?
    【解决方案2】:
    library(dplyr)
    library(purrr)
    library(tidyr)
    
    test %>% 
      as_tibble() %>%                                  # dplyr
      mutate(category = map(category, as_tibble)) %>%  # purrr
      unnest(cols = "category") %>%                    # tidyr
      unnest(cols = "subcat")
    
    # A tibble: 6 x 2
      name  subcat
      <chr> <chr> 
    1 A     1     
    2 A     2     
    3 A     3     
    4 B     4     
    5 B     5     
    6 B     6  
    

    这种方法将您的列表转换为数据框,然后将列表中的每个列表元素转换为数据框,然后依次取消嵌套。

    【讨论】:

      【解决方案3】:

      我们可以在base Rstack 中做到这一点

      stack(test)[2:1]
      #   ind values
      #1   A      1
      #2   A      2
      #3   A      3
      #4   B      4
      #5   B      5
      #6   B      6
      

      或者使用unlist/data.frame

      data.frame(name = rep(names(test), lengths(test)), val = unlist(test))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-22
        • 1970-01-01
        • 2018-03-08
        • 1970-01-01
        • 2021-12-13
        • 2019-05-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多