Expand nested dataframe cell in long format

891 Views Asked by At

Have fetched info from mongo and it looks like this :

enter image description here

I want to expand part_list in such a way it looks like this :

enter image description here

Have checked this solution ( Expand nested dataframe into parent ), but it seems to not work in my case.

Also I am unable to create a dataframe like this to post a reproducible code here. How should I expand it ?

2

There are 2 best solutions below

0
On BEST ANSWER

You can use unnest() in tidyr to expand a nested column.

tidyr::unnest(df, part_list)

# # A tibble: 3 x 2
#   chapterid part_list
#   <chr>     <chr>    
# 1 a         c        
# 2 a         d        
# 3 b         e 

Data

df <- data.frame(chapterid = c("a", "b"))
df$part_list <- list(c("c", "d"), "e")

#   chapterid part_list
# 1         a      c, d
# 2         b         e
0
On

Here is a base R option (Thanks for example data from @Darren Tsai)

dfout <- setNames(with(df,data.frame(rep(chapterid,lengths(part_list)),unlist(part_list))),names(df))

which gives

> dfout
  chapterid part_list
1         a         c
2         a         d
3         b         e