【问题标题】:Extract a dataframe from a column of dataframes (tidyverse approach)从数据框列中提取数据框(tidyverse 方法)
【发布时间】:2018-02-05 13:32:53
【问题描述】:

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

这可行,但似乎不是 tidyverse-ish:

# 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]]

标签: r dplyr purrr


【解决方案1】:

更好的解决方案:

使用tidyr::unnest():

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

其他解决方案:

你可以使用pull(tidyverse的方式来选择列,相当于$),但是它返回的是一个单元素的小标题列表,所以你需要在末尾添加%&gt;% .[[1]]

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

【讨论】:

  • 请注意这里的第二个pull() 解决方案:我认为可以删除select() 行以达到相同的结果。
猜你喜欢
  • 2019-12-25
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
相关资源
最近更新 更多