简体   繁体   English

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

[英]How to use `dplyr::filter` inside `purrr::map`

Here is a very simple function which returns a list when using map这是一个非常简单的 function 使用map时返回一个列表

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

I want to create a similar function which can filter based on a keyword and returns a vector.我想创建一个类似的 function 可以根据关键字过滤并返回一个向量。 So this is what I made所以这就是我做的



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)
}

As you can see the function works fine when I use it alone如您所见,当我单独使用 function 时工作正常

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

But when I use this in a map it is not working但是当我在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

I know I'm making a very basic mistake here but couldn't figure out what.我知道我在这里犯了一个非常基本的错误,但不知道是什么。

I don't see why you need map2() , which requires two lists.我不明白为什么需要map2() ,它需要两个列表。 You might run it with map() .您可以使用map()运行它。 That said, you do need to specify fliter_func() 's dff value.也就是说,您确实需要指定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

You need map with proper function call instead of map_2您需要map和正确的 function 调用而不是map_2

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

Output Output

[[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM