【问题标题】:Unnest a list and retain names取消嵌套列表并保留名称
【发布时间】:2020-04-10 16:26:25
【问题描述】:

我怀疑这是一个小问题,但我想不通。 我有一个生成此列表数据的打包函数的输出:

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") 其中参数 = 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。

【问题讨论】:

  • 如果要转换成data.frame,就是data.frame(output[[1]]),但是听起来好像比较复杂?

标签: r list dplyr purrr


【解决方案1】:

如果您查看对象的类

> class(output)
[1] "list"

> class(output[[1]])
[1] "matrix"

你可以这样做:

library(magrittr)
df <- as.data.frame(output) %>% tibble::rownames_to_column("Parameter")

  Parameter  Estimate        SE    X95..LCI X95..UCI
1         N 69.000000 5.1000000 46.90000000 90.70000
2         k  1.522248 0.3622561 -0.03641383  3.08091

【讨论】:

  • 谢谢,这在“功能化”时效果很好,因此可以通过 map() 在整个数据集上应用。
【解决方案2】:

您可以使用以下内容:

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

【讨论】:

  • 谢谢,这可行,但另一个解决方案对我的应用程序来说更干净一些(将其放入一个函数中,然后将其映射到另一个数据集)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-31
  • 2019-05-01
  • 1970-01-01
  • 2019-07-17
  • 2020-07-08
相关资源
最近更新 更多