[英]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并希望将其转换为这样的 data.frame
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
这是一个带有
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]>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.