我已经能够使用 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
(选择列的 tidyverse 方法,相当于 $
),但它返回一个单元素的 tibbles 列表,因此您需要添加 %>% .[[1]]
到最后。
meta_df %>%
dplyr::filter(df_name == "Two") %>%
dplyr::pull(dfs) %>% .[[1]]
关于r - 从一列数据帧中提取数据帧(tidyverse 方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623753/