使用整洁的方法将命名列表列表转换为数据框

Convert named list of lists to dataframe using tidy approach

我正在尝试使用整洁的函数(例如 purrr 中可用的函数)将命名的列表列表转换为数据框。我尝试了 here and 的解决方案,但它们都不适合我(例如,行不是单个观察值)。此外,这两个选项都没有提供有关如何使对象(?)名称(例如 e1m1_fit 和 e2m2a_fit)与数据框中的新行相关联的解决方案。

library("tidyverse")

# The named list I am trying to convert to a dataframe/tibble:
df <-
  list(e1m1_fit = structure(list(term = c("(Intercept)", "log10(q)"), 
                                 estimate = c(2.7, -0.1), std.error = c(0.03, 0.01), 
                                 statistic = c(88.04, -15.55), 
                                 p.value = c(0.01, 0.01)), 
                            class = c("tbl_df", "tbl", "data.frame"), 
                            row.names = c(NA, -2L)), 
       e2m2a_fit = structure(list(term = c("(Intercept)", "log10(q)"), 
                                  estimate = c(2.7, -0.1), 
                                  std.error = c(0.03, 0.01), 
                                  statistic = c(79.78, -15.48), 
                                  p.value = c(0.01, 0.01)), 
                             class = c("tbl_df", "tbl", "data.frame"), 
                             row.names = c(NA, -2L)))

# I tried a solution like this, but a) it's not generalized/it's very specific to this example. 
# And I cannot figure out how to associate the correct parameter/coefficient estimate with the correct value (they all end up in the same row). 
# Also, it does not pass along the object name (e.g., e1m1_fit) to the new dataframe/tibble.

# A solution I tried that doesn't accomplish what I want:
df2 <- 
  df %>% 
  tibble(term = map(., "term"),
         estimate = map(., "estimate"),
         std_error = map(., "std.error"),
         statistic = map(., "statistic"),
         p_val = map(., "p.value")
         ) %>% 
  mutate(term1 = map_chr(term, 1),
         term2 = map_chr(term, 2),
         estimate1 = map_dbl(estimate, 1),
         estimate2 = map_dbl(estimate, 2))

非常感谢任何帮助!

我们可以使用 bind_rows,其中 .idlist

names 创建一个新列
library(dplyr)
 bind_rows(df, .id = "fitname")
# A tibble: 4 × 6
  fitname   term        estimate std.error statistic p.value
  <chr>     <chr>          <dbl>     <dbl>     <dbl>   <dbl>
1 e1m1_fit  (Intercept)      2.7      0.03      88.0    0.01
2 e1m1_fit  log10(q)        -0.1      0.01     -15.6    0.01
3 e2m2a_fit (Intercept)      2.7      0.03      79.8    0.01
4 e2m2a_fit log10(q)        -0.1      0.01     -15.5    0.01

此外,如果 df list 是通过使用 map 循环创建的,_dfr 可以 return 单个 tibble/data.frame.id 指定为 list

的名称
library(purrr)
map_dfr(yourlist, ~ yourfun(.x), .id = "fitname")