【问题标题】:nested list to data frame嵌套列表到数据框
【发布时间】:2020-05-21 20:42:21
【问题描述】:

从嵌套列表创建数据框

经过一些迭代,我创建了一组具有以下架构的嵌套列表(用于数千种产品)

My_list <- list()
My_list$'product1' <- list()
My_list$'product1'[[1]] <- list()
My_list$'product1'[[2]] <- list()
My_list$'product2' <- list()
My_list$'product2'[[1]] <- list()
My_list$'product2'[[2]] <- list()

My_list$'product1'[[1]]$A <- 1
My_list$'product1'[[1]]$B <- 2
My_list$'product1'[[2]]$A <- 3
My_list$'product1'[[2]]$B <- 4
My_list$'product2'[[1]]$A <- 5
My_list$'product2'[[1]]$B <- 6

我想把它转换成具有以下结构的数据框

data.frame(sku=c("product1","product1","product2"),Item=c("1","2","1"),A=c(1,3,5), B=c(2,4,6))

【问题讨论】:

    标签: r list dataframe nested


    【解决方案1】:

    这是unnest_wider的一个选项

    library(tidyr)
    library(dplyr)
    library(tibble)
    library(data.table)
    enframe(My_list, name = "sku") %>%
        unnest(c(value)) %>% 
        unnest_wider(c(value)) %>%
        na.omit %>%
        mutate(Item = rowid(sku))
    # A tibble: 3 x 4
    #  sku          A     B  Item
    #  <chr>    <dbl> <dbl> <int>
    #1 product1     1     2     1
    #2 product1     3     4     2
    #3 product2     5     6     1
    

    base R

    lst1 <- lapply(My_list,  function(x) do.call(rbind,  lapply(x, as.data.frame)))
    do.call(rbind, Map(cbind, sku = names(lst1), lst1))
    

    【讨论】:

    • 谢谢!基本 R 解决方案目前对我来说很好:)
    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    相关资源
    最近更新 更多