问题
I have the following list
my_list <- list(`3920_0` = structure(c(623700, 96400), .Dim = 1:2, .Dimnames = list("1", c("X", "Y"))),
`3864_0` = structure(c(665100, 167400), .Dim = 1:2, .Dimnames = list("1", c("X", "Y"))),
`1948_1` = structure(c(589800, 97900), .Dim = 1:2, .Dimnames = list("1", c("X", "Y"))))
looking as follows
$`3920_0`
X Y
1 623700 96400
$`3864_0`
X Y
1 665100 167400
$`1948_1`
X Y
1 589800 97900
When I use enframe
I get the following
# A tibble: 3 x 2
name value
<chr> <list>
1 3920_0 <dbl[,2] [1 x 2]>
2 3864_0 <dbl[,2] [1 x 2]>
3 1948_1 <dbl[,2] [1 x 2]>
That is almost what I want, however I would like to "split" the list in the "value" column into two columns "X" and "Y".
Alternatively, would there be a better solution to achieve the final table without enframe()?
回答1:
You can use unnest_wider
after enframe
:
my_list %>%
tibble::enframe() %>%
tidyr::unnest_wider(value, names_repair = ~c('name','x', 'y'))
# name x y
# <chr> <dbl> <dbl>
#1 3920_0 623700 96400
#2 3864_0 665100 167400
#3 1948_1 589800 97900
if you want to do this without enframe
, a solution similar to @Sotos using purrr::map_df
purrr::map_df(my_list, as.data.frame,.id = 'name')
回答2:
Having data frames in a list helps with output structure when you binding. So,
dplyr::bind_rows(lapply(my_list, data.frame), .id = 'id')
# id X Y
#1...1 3920_0 623700 96400
#1...2 3864_0 665100 167400
#1...3 1948_1 589800 97900
回答3:
Another option using rbindlist:
library(data.table)
rbindlist(lapply(my_list, data.frame), idcol = 'name')
name X Y
1: 3920_0 623700 96400
2: 3864_0 665100 167400
3: 1948_1 589800 97900
回答4:
We can also convert to tibble
and bind them together
library(purrr)
library(tibble)
map_dfr(my_list, as_tibble, .id = 'name')
# A tibble: 3 x 3
# name X Y
# <chr> <dbl> <dbl>
#1 3920_0 623700 96400
#2 3864_0 665100 167400
#3 1948_1 589800 97900
来源:https://stackoverflow.com/questions/63613264/transform-a-list-column-in-a-tibble-to-multiple-columns-after-using-enframe-from