r - 取消嵌套列表并保留名称
问题描述
我怀疑这是一个微不足道的问题,但我无法弄清楚。我有一个生成此列表数据的打包函数的输出:
output <- list(structure(c(69, 1.52224832314379, 5.1, 0.362256088534843,
46.9, -0.0364138250590129, 90.7, 3.0809104713466), .Dim = c(2L,
4L), .Dimnames = list(structure(c("N", "k"), .Dim = 1:2), c("Estimate",
"SE", "95% LCI", "95% UCI"))))
我想把它变成一个数据框,列 c("Parameter", "Estimate", "SE", "95% LCI", "95% UCI") where Parameter = c("N", "k")
我试过 dplyr::unnest(output) no applicable method for 'unnest' applied to an object of class "list"
, unlist(output) ,它返回c(69, 1.52224832314379, 5.1, 0.362256088534843,
46.9, -0.0364138250590129, 90.7, 3.0809104713466)
但不保留任何名称。purrr::flatten(output) 也不保留任何名称。
顺便说一句,我也不知道如何将名称从列表中提取出来——dimnames() 和 names() 返回 NULL。
解决方案
您可以使用以下内容:
library(tidyverse) # alternatively, you can load purrr and dplyr libraries only
output %>%
pluck(1) %>%
as_tibble(rownames = NA) %>%
rownames_to_column(var = "Parameter")
# A tibble: 2 x 5
parameter Estimate SE `95% LCI` `95% UCI`
<chr> <dbl> <dbl> <dbl> <dbl>
1 N 69 5.1 46.9 90.7
2 k 1.52 0.362 -0.0364 3.08