在嵌套数据框内使用filter()(和其他dplyr函数)和map()

Tar*_*aas 10 r dplyr purrr tidyverse

我试图使用map()purrr包装应用filter()功能,存储在嵌套数据帧中的数据.

"你为什么不先过滤,然后窝? - 你可能会问.这会起作用(我会用这样的过程显示我想要的结果),但我正在寻找方法来做到这一点purrr.我想要只有一个数据框,有两个列表列,都是嵌套数据帧 - 一个是完整的,一个是过滤的.

我现在可以通过执行nest()两次来实现它:一次打开所有数据,第二次打开过滤数据:

library(tidyverse)

df <- tibble(
  a = sample(x = rep(c('x','y'),5), size = 10),
  b = sample(c(1:10)),
  c = sample(c(91:100))
)

df_full_nested <- df %>% 
  group_by(a) %>% 
  nest(.key = 'full')

df_filter_nested <- df %>%
  filter(c >= 95) %>%  ##this is the key step
  group_by(a) %>% 
  nest(.key = 'filtered')

## Desired outcome - one data frame with 2 nested list-columns: one full and one filtered.
## How to achieve this without breaking it out into 2 separate data frames?
df_nested <- df_full_nested %>% 
  left_join(df_filter_nested, by = 'a')
Run Code Online (Sandbox Code Playgroud)

对象看起来像这样:

> df
# A tibble: 10 x 3
       a     b     c
   <chr> <int> <int>
 1     y     8    93
 2     x     9    94
 3     y    10    99
 4     x     5    97
 5     y     2   100
 6     y     3    95
 7     x     7    96
 8     y     6    92
 9     x     4    91
10     x     1    98

> df_full_nested
# A tibble: 2 x 2
      a             full
  <chr>           <list>
1     y <tibble [5 x 2]>
2     x <tibble [5 x 2]>

> df_filter_nested
# A tibble: 2 x 2
      a         filtered
  <chr>           <list>
1     y <tibble [3 x 2]>
2     x <tibble [3 x 2]>

> df_nested
# A tibble: 2 x 3
      a             full         filtered
  <chr>           <list>           <list>
1     y <tibble [5 x 2]> <tibble [4 x 2]>
2     x <tibble [5 x 2]> <tibble [4 x 2]>
Run Code Online (Sandbox Code Playgroud)

所以,这很有效.但它不干净.在现实生活中,我按几列分组,这意味着我还必须加入几个列......它变得毛茸茸.

我想知道是否有办法将过滤器应用于嵌套列.这样,我就可以在同一个对象中操作.更干净,更容易理解的代码.

我觉得它看起来像

df_full_nested %>% mutate(filtered = map(full, ...))
Run Code Online (Sandbox Code Playgroud)

但我不确定如何filter()正确映射

谢谢!

Psi*_*dom 16

您可以使用map(full, ~ filter(., c >= 95)),.代表单个嵌套的tibble,您可以直接应用过滤器:

df_nested_2 <- df_full_nested %>% mutate(filtered = map(full, ~ filter(., c >= 95)))

identical(df_nested, df_nested_2)
# [1] TRUE
Run Code Online (Sandbox Code Playgroud)

  • 对于可能会发现此内容并正在寻找文档的 googlers,有关此信息的重要来源是 [_R for Data Science_ 中的许多模型章节](https://r4ds.had.co.nz/many-models.html ) (2认同)