R到data.frame的命名列表列表



我有一个类似的列表

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

并希望将其转换为类似的数据帧

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

我试过

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

但我不知道该怎么做。

您可以使用:

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]>

这里有一个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]>

相关内容

最新更新