Lucas
Lucas

Reputation: 589

nested list to data frame

create data frame from nested list

after some iterations I have created a set of nested lists with the following schema (for thousands of products)

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

And I want to transform it into a data frame with the following structure

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

Upvotes: 2

Views: 95

Answers (1)

akrun
akrun

Reputation: 886938

Here is one option with 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

Or with 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))

Upvotes: 2

Related Questions