且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将列表列表转换为小标题(数据框)

更新时间:2022-12-12 09:10:01

使用 tidyverse ,您可以使用 purrr 来帮助您

Using tidyverse, you could use purrr to help you




library(dplyr)
library(purrr)

tibble(
  pair = map(lol, "pair"),
  genes_vec = map_chr(lol, "genes")
) %>% 
  mutate(
    pair1 = map_chr(pair, 1),
    pair2 = map_chr(pair, 2) 
  ) %>%
  select(pair1, pair2, genes_vec)
#> # A tibble: 3 x 3
#>        pair1     pair2 genes_vec
#>        <chr>     <chr>     <chr>
#> 1 BoneMarrow Pulmonary     PRR11
#> 2 BoneMarrow Umbilical    GNB2L1
#> 3  Pulmonary Umbilical    ATP1B1






要保留 map_chr(lol, genes)替换为 map(lol2, genes)带有列表列的嵌套数据框。


with the second example, just replace map_chr(lol, "genes") with map(lol2, "genes") as you want to keep a nested dataframe with a list column.




tibble(
  pair = map(lol2, "pair"),
  genes_vec = map(lol2, "genes")
) %>% 
  mutate(
    pair1 = map_chr(pair, 1),
    pair2 = map_chr(pair, 2) 
  ) %>%
  select(pair1, pair2, genes_vec)
#> # A tibble: 3 x 3
#>        pair1     pair2 genes_vec
#>        <chr>     <chr>    <list>
#> 1 BoneMarrow Pulmonary <chr [2]>
#> 2 BoneMarrow Umbilical <chr [1]>
#> 3  Pulmonary Umbilical <chr [1]>






更通用的方法是与嵌套的小对象,并根据需要将它们取消嵌套


And a more generic approach would be to work with nested tibbles and unnest them as needed

library(dplyr)
library(purrr)
library(tidyr)

tab1 <-lol %>%
  transpose() %>%
  as_tibble() %>%
  mutate(pair = map(pair, ~as_tibble(t(.x)))) %>%
  mutate(pair = map(pair, ~set_names(.x, c("pair1", "pair2"))))
tab1
#> # A tibble: 3 x 2
#>               pair     genes
#>             <list>    <list>
#> 1 <tibble [1 x 2]> <chr [1]>
#> 2 <tibble [1 x 2]> <chr [1]>
#> 3 <tibble [1 x 2]> <chr [1]>

对于 lol2 ,除非列表 lol2 而不是 lol1

For lol2 nothing changes unless the list lol2 instead of lol1

tab2 <- lol2 %>%
  transpose() %>%
  as_tibble() %>%
  mutate(pair = map(pair, ~as_tibble(t(.x)))) %>%
  mutate(pair = map(pair, ~set_names(.x, c("pair1", "pair2"))))
tab2
#> # A tibble: 3 x 2
#>               pair     genes
#>             <list>    <list>
#> 1 <tibble [1 x 2]> <chr [2]>
#> 2 <tibble [1 x 2]> <chr [1]>
#> 3 <tibble [1 x 2]> <chr [1]>

然后您可以取消嵌套想要的列

You can then unnest what the column you want

tab1 %>%
  unnest()
#> # A tibble: 3 x 3
#>    genes      pair1     pair2
#>    <chr>      <chr>     <chr>
#> 1  PRR11 BoneMarrow Pulmonary
#> 2 GNB2L1 BoneMarrow Umbilical
#> 3 ATP1B1  Pulmonary Umbilical

tab2 %>% 
  unnest(pair)
#> # A tibble: 3 x 3
#>       genes      pair1     pair2
#>      <list>      <chr>     <chr>
#> 1 <chr [2]> BoneMarrow Pulmonary
#> 2 <chr [1]> BoneMarrow Umbilical
#> 3 <chr [1]>  Pulmonary Umbilical