问题
For example, I have a tidy data frame like this:
df <- tibble(id=1:2,
ctn=list(list(a="x",b=1),
list(a="y",b=2)))
# A tibble: 2 x 2
id ctn
<int> <list>
1 1 <list [2]>
2 2 <list [2]>
How could I unnest ctn
column to the right so that the data frame will be like this:
# A tibble: 2 x 3
id a b
<int> <chr> <dbl>
1 1 x 1
2 2 y 2
回答1:
With dplyr
and purrr
df %>%
mutate(ctn = map(ctn, as_tibble)) %>%
unnest()
# A tibble: 2 x 3 id a b <int> <chr> <dbl> 1 1 x 1 2 2 y 2
回答2:
One option is
library(data.table)
setDT(df)[, unlist(ctn, recursive = FALSE), id]
# id a b
#1: 1 x 1
#2: 2 y 2
Or with tidyr
library(tidyverse)
df$ctn %>%
setNames(., df$id) %>%
bind_rows(., .id = 'id')
# A tibble: 2 x 3
# id a b
# <chr> <chr> <dbl>
#1 1 x 1
#2 2 y 2
来源:https://stackoverflow.com/questions/45328221/unnest-one-column-list-to-many-columns-in-tidyr