从一列数据帧中提取数据帧(tidyverse 方法)

Extract a dataframe from a column of dataframes (tidyverse approach)

我已经能够使用 purrr 做一些不错的事情,以便能够处理数据帧中的数据帧列。我指的是数据框的一列,其中每个单元格本身都包含一个数据框。

我正在尝试找出提取这些数据帧之一的惯用方法。

例子

# Create a couple of dataframes:
df1 <- tibble::tribble(~a, ~b,
                        1,  2,
                        3,  4)
df2 <- tibble::tribble(~a, ~b,
                       11, 12,
                       13, 14)

# Make a dataframe with a dataframe column containing 
# our first two dfs as cells:
meta_df <- tibble::tribble(~df_name, ~dfs, 
                           "One",     df1, 
                           "Two",     df2)

我的问题是,从 meta_df 中取回这些数据帧之一的 tidyverse 首选方法是什么?假设我使用 select()filter():

得到了我想要的单元格
library("magrittr")
# This returns a 1x1 tibble with the only cell containing the 2x2 tibble that
# I'm actually after:
meta_df %>%
  dplyr::filter(df_name == "Two") %>%
  dplyr::select(dfs)

这有效,但似乎不整洁:

# To get the actual tibble that I'm after I can wrap the whole lot in brackets
# and then use position [[1, 1]] index to get it:
(meta_df %>%
  dplyr::filter(df_name == "Two") %>%
  dplyr::select(dfs))[[1, 1]]

# Or a pipeable version:
meta_df %>%
  dplyr::filter(df_name == "Two") %>%
  dplyr::select(dfs) %>%
  `[[`(1, 1)

我觉得这可能是答案在 purrr 而不是 dplyr 的情况,一旦你知道它可能是一个简单的技巧,但我到目前为止一片空白。

更好的解决方案:

使用tidyr::unnest():

meta_df %>%
  dplyr::filter(df_name == "Two") %>%
  dplyr::select(dfs) %>%
  tidyr::unnest()

其他解决方案:

您可以使用 pull(select 列的 tidyverse 方法,相当于 $),但它 returns 是一个单元素列表,所以你需要在最后添加%>% .[[1]]

meta_df %>%
  dplyr::filter(df_name == "Two") %>%
  dplyr::pull(dfs) %>% .[[1]]