如何在 `purrr::map` 中使用 `dplyr::filter`

How to use `dplyr::filter` inside `purrr::map`

这是一个非常简单的函数,当使用 map

时 returns 一个列表
library(tidyverse)


simple_function <- function(x,y){
 c(x+y, y-x)
}


1:3 %>% 
  map2(5,simple_function)
#> [[1]]
#> [1] 6 4
#> 
#> [[2]]
#> [1] 7 3
#> 
#> [[3]]
#> [1] 8 2

我想创建一个类似的函数,它可以根据关键字和 returns 矢量进行过滤。这就是我做的



df <- structure(list(to_filter = c("YY", "XX", "XX", "YY", "XX", "XX", 
                                 "YY", "YY", "YY", "YY", "ZZ", "YY", "ZZ", "YY", "YY", "XX", "YY", 
                                 "YY", "YY", "YY"), num = c(1L, 2L, 2L, 4L, 2L, 3L, 3L, 5L, 3L, 
                                                            1L, 4L, 5L, 1L, 2L, 5L, 1L, 1L, 3L, 5L, 5L)), row.names = c(NA, 
                                                                                                                        -20L), class = c("tbl_df", "tbl", "data.frame"))

filter_func <- function(name, dff){
  dff %>% 
    filter(to_filter == name) %>% 
    pull(num)
}

如你所见,当我单独使用时,该功能运行良好

filter_func("YY", df)
#>  [1] 1 4 3 5 3 1 5 2 5 1 3 5 5

但是当我在 map 中使用它时它不起作用


df %>% 
  pull(to_filter) %>% 
  unique() %>% 
  map2(df, filter_func)
#> Error: Mapped vectors must have consistent lengths:
#> * `.x` has length 3
#> * `.y` has length 2

我知道我在这里犯了一个非常基本的错误,但无法弄清楚是什么。

您需要 map 和适当的函数调用而不是 map_2

df %>% 
  pull(to_filter) %>% 
  unique() %>% 
  map(., .f = function(x) { filter_func(name = x, dff = df) })

输出

[[1]]
 [1] 1 4 3 5 3 1 5 2 5 1 3 5 5

[[2]]
[1] 2 2 2 3 1

[[3]]
[1] 4 1

我不明白你为什么需要 map2(),它需要两个列表。你可以 运行 它与 map()。 也就是说,您确实需要指定 fliter_func() 的 dff 值。

df %>% 
    pull(to_filter) %>% 
    unique() %>% 
    map(.f = filter_func, dff = df)

[[1]]
 [1] 1 4 3 5 3 1 5 2 5 1 3 5 5

[[2]]
[1] 2 2 2 3 1

[[3]]
[1] 4 1