Reputation: 3047
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.
Upvotes: 1
Views: 51
Reputation: 887118
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]>
Upvotes: 1
Reputation: 388982
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]>
Upvotes: 1