Home > Back-end >  How to convert table with row with lists of lists to data.frame with more rows and more columns?
How to convert table with row with lists of lists to data.frame with more rows and more columns?

Time:11-13

How to convert "source" to "result":

l1 <- list(list(list(item=list(category="item category",name="item name"))))
l2 <- list(
  list(
    list(
      item=list(category="item category1",name="item name1"),
      item=list(category="item category2",name="item name2")
      )))
source <- tribble(
  ~order, ~tablePart,
  1,l1,
  2,l2
  )

result <- tribble(
  ~order, ~category, ~name,
  1,"item category","item name",
  2,"item category1","item name1",
  2,"item category2","item name2"
)

CodePudding user response:

As you have a nested list column we could use flatten_dfc and then unnest:

library(dplyr)
library(purrr)
library(tidyr)

source %>% 
  mutate(tablePart = map(tablePart, flatten_dfc)) %>% 
  unnest()
  order category      name      category...1   name...2   category...3   name...4  
  <dbl> <chr>         <chr>     <chr>          <chr>      <chr>          <chr>     
1     1 item category item name NA             NA         NA             NA        
2     2 NA            NA        item category1 item name1 item category2 item name2

CodePudding user response:

Or in data.table way

library(data.table)
source <- source %>% data.table()
source[, rbindlist(tablePart[[1]][[1]][[1]]), order] 
  •  Tags:  
  • r
  • Related