Mike Booth
Mike Booth

Reputation: 69

Unnest a list and retain names

I suspect this is a trivial problem, but I can't figure it out. I have output from a packaged function that generates this list data:

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"))))

I want to turn this into a data frame with columns c("Parameter", "Estimate", "SE", "95% LCI", "95% UCI") where Parameter = c("N", "k")

I've tried dplyr::unnest(output) no applicable method for 'unnest' applied to an object of class "list", unlist(output) which returns c(69, 1.52224832314379, 5.1, 0.362256088534843, 46.9, -0.0364138250590129, 90.7, 3.0809104713466) but does not retain any of the names. purrr::flatten(output) also does not retain any of the names.

Incidentally, I also can't figure out how to pull the names out of the list - dimnames() and names() return NULL.

Upvotes: 0

Views: 1588

Answers (2)

davidnortes
davidnortes

Reputation: 932

If you look at the classes of your objects

> class(output)
[1] "list"

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

You could simply do:

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

Upvotes: 1

Junitar
Junitar

Reputation: 999

You can use the following:

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

Upvotes: 1

Related Questions