Unnest one column list to many columns in tidyr

空扰寡人 提交于 2019-12-07 12:58:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!