R: How to “unnest” a nested list into data.frame?

a 夏天 提交于 2021-02-10 22:18:04

问题


I have

l1 = list(SeriousDlqin2yrs = list(prediction = "0", prediction_probs = list(`0` = 0.5, `1` = 0.5)))
l2 = list(SeriousDlqin2yrs = list(prediction = "1", prediction_probs = list(`0` = 0.6, `1` = 0.4)))

l12 = list(l1, l2)

data.frame.output = l12 %>% 
  purrr::reduce(dplyr::bind_rows) %>% 
  unnest(cols = c("SeriousDlqin2yrs", "0", "1"))

and I am expect a dataframe like this (expressed in CSV format)

SeriousDlqin2yrs$prediction, SeriousDlqin2yrs$prediction$0, SeriousDlqin2yrs$prediction$1
0, 0.5, 0.5
0, 0.6, 0.4

Preferably I would need a solution where it works regardless of the names into the list.


回答1:


We could also use as.data.frame and this gets the correct type

out <- map_dfr(l12, as.data.frame)
str(out)
#'data.frame':  2 obs. of  3 variables:
# $ SeriousDlqin2yrs.prediction        : chr  "0" "1"
# $ SeriousDlqin2yrs.prediction_probs.0: num  0.5 0.6
# $ SeriousDlqin2yrs.prediction_probs.1: num  0.5 0.4

Or in base R

do.call(rbind, lapply(l12, as.data.frame))
#  SeriousDlqin2yrs.prediction SeriousDlqin2yrs.prediction_probs.0 SeriousDlqin2yrs.prediction_probs.1
#1                           0                                 0.5                                 0.5
#2                           1                                 0.6                                 0.4



回答2:


You can do :

purrr::map_dfr(l12, unlist)

# A tibble: 2 x 3
#  SeriousDlqin2yrs.prediction SeriousDlqin2yrs.prediction_probs.0 SeriousDlqin2yrs.prediction_probs.1
#  <chr>                       <chr>                               <chr>                              
#1 0                           0.5                                 0.5                                
#2 1                           0.6                                 0.4                   

Or in base R :

as.data.frame(do.call(rbind, lapply(l12, unlist)))



回答3:


The above is correct, but using {rlist} maintains type correctness

library(rlist)

purrr::map_dfr(l12, rlist::list.flatten)


来源:https://stackoverflow.com/questions/63275653/r-how-to-unnest-a-nested-list-into-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!