简体   繁体   English

将一列列表取消嵌套到 tidyr 中的多列

[英]Unnest one column list to many columns in tidyr

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:我怎么能在右侧取消嵌套ctn列,以便数据框如下所示:

# A tibble: 2 x 3
     id     a     b
  <int> <chr> <dbl>
1     1     x     1
2     2     y     2

With dplyr and purrr使用dplyrpurrr

df %>% 
  mutate(ctn = map(ctn, as_tibble)) %>%
  unnest()
 # A tibble: 2 x 3 id ab <int> <chr> <dbl> 1 1 x 1 2 2 y 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或者用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

In a tidy way we can now (dplyr 1.0.2 and above) do this using rowwise() :我们现在可以以一种整洁的方式(dplyr 1.0.2及更高版本)使用rowwise()执行此操作:

df %>% rowwise() %>% mutate(as_tibble(ctn))
# A tibble: 2 x 4
# Rowwise: 
     id ctn              a         b
  <int> <list>           <chr> <dbl>
1     1 <named list [2]> x         1
2     2 <named list [2]> y         2

And sticking to purrr we can also:坚持purrr我们还可以:

df %>% mutate(map_dfr(ctn, as_tibble))
# A tibble: 2 x 4
     id ctn              a         b
  <int> <list>           <chr> <dbl>
1     1 <named list [2]> x         1
2     2 <named list [2]> y         2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM