从数据框列中提取数据框(使用tidyverse方法)

3

我已经使用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)

我的问题是,获取其中一个数据框的整洁宇宙首选方法是什么?假设我使用 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)

这个可以用,但似乎不符合tidyverse的风格:

# 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的情况,并且一旦您知道它,它可能是一个简单的技巧,但到目前为止我还没有想出来。


也许可以使用 keep 函数,例如 keep(meta_df$dfs, meta_df$df_name == "One")[[1]] - akrun
1个回答

3

更好的解决方案:

使用tidyr::unnest()函数:

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

其他解决方案:

你可以使用 pull (选择列的tidyverse方式,等同于$),但它返回一个tibbles的一元素列表,因此需要在末尾添加%>% .[[1]]

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

1
这里关于第二个 pull() 解决方案的说明:我认为可以删除 select() 行以达到相同的结果。 - jamse

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接