取消引用R dplyr函数中的函数列表

时间:2019-03-28 11:49:02

标签: r dplyr purrr

我试图将函数列表传递给dplyr summerize_at函数并收到警告:

library(tidyverse)
library(purrr)

p <- c(0.2, 0.5, 0.8)

p_names <- map_chr(p, ~paste0(.x*100, "%"))

p_funs <- map(p, ~partial(quantile, probs = .x, na.rm = TRUE)) %>% 
  set_names(nm = p_names)

mtcars %>% 
  group_by(cyl) %>% 
  summarize_at(vars(mpg), funs(!!!p_funs))
#> Warning: funs() is soft deprecated as of dplyr 0.8.0
#> please use list() instead
#> 
#> # Before:
#> funs(name = f(.)
#> 
#> # After: 
#> list(name = ~f(.))
#> This warning is displayed once per session.
#> # A tibble: 3 x 4
#>     cyl `20%` `50%` `80%`
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     4  22.8  26    30.4
#> 2     6  18.3  19.7  21  
#> 3     8  13.9  15.2  16.8

然后,我将funs更改为list,但是找不到取消引用乐趣列表的方法。

mtcars %>% 
  group_by(cyl) %>% 
  summarize_at(vars(mpg), list(~ !!!p_funs))
#> Error in !p_funs: invalid argument type

mtcars %>% 
  group_by(cyl) %>% 
  summarize_at(vars(mpg), list(~ {{p_funs}}))
#> Error: Column `mpg` must be length 1 (a summary value), not 3

1 个答案:

答案 0 :(得分:3)

list不支持拼接(!!!),请改用list2lst

mtcars %>% 
  group_by(cyl) %>% 
  summarize_at(vars(mpg), rlang::list2(!!!p_funs))
# # A tibble: 3 x 4
#     cyl `20%` `50%` `80%`
#   <dbl> <dbl> <dbl> <dbl>
# 1     4  22.8  26    30.4
# 2     6  18.3  19.7  21  
# 3     8  13.9  15.2  16.8

mtcars %>% 
  group_by(cyl) %>% 
  summarize_at(vars(mpg), lst(!!!p_funs))
# # A tibble: 3 x 4
#     cyl `20%` `50%` `80%`
#   <dbl> <dbl> <dbl> <dbl>
# 1     4  22.8  26    30.4
# 2     6  18.3  19.7  21  
# 3     8  13.9  15.2  16.8

尽管这里最简单的方法是:

mtcars %>% 
  group_by(cyl) %>% 
  summarize_at(vars(mpg), p_funs)
# # A tibble: 3 x 4
#     cyl `20%` `50%` `80%`
#   <dbl> <dbl> <dbl> <dbl>
# 1     4  22.8  26    30.4
# 2     6  18.3  19.7  21  
# 3     8  13.9  15.2  16.8