简体   繁体   中英

R list of named lists to data.frame

I have a list like this

lst <- list(
  r = list(
    c(1:3),
    c(2:4)
  ),
  c = list(
    c(3:5),
    c(4:6)
  )
)

and would like to transform it to a data.frame like this

desired_output <- bind_rows(
  tibble(name = "r1", value = c(1:3) %>% list),
  tibble(name = "r2", value = c(2:4) %>% list),
  tibble(name = "c1", value = c(3:5) %>% list),
  tibble(name = "c2", value = c(4:6) %>% list)
)

I tried

lst %>%
  imap(~set_names(.x, paste0(.y, seq_along(.x))))

but then I am not sure how to follow.

You can use:

purrr::imap_dfr(lst, ~tibble(name = paste0(.y, seq_along(.x)), value = .x))

#  name  value    
#  <chr> <list>   
#1 r1    <int [3]>
#2 r2    <int [3]>
#3 c1    <int [3]>
#4 c2    <int [3]>

Here is an option with enframe

library(tibble)
library(dplyr)
library(stringr)
library(tidyr)
enframe(lst) %>% 
   unnest(c(value)) %>%
   mutate(name = str_c(name, data.table::rowid(name)))
# A tibble: 4 x 2
#  name  value    
#  <chr> <list>   
#1 r1    <int [3]>
#2 r2    <int [3]>
#3 c1    <int [3]>
#4 c2    <int [3]>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM