unquote a list of functions inside R dplyr functions

纵然是瞬间 提交于 2019-12-24 03:23:51

问题


I was trying to pass a list of functions into dplyr summerize_at function and got a warning:

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

I then changed the funs to list but couldn't find a way to unquote the list of funs.

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:


list doesn't support splicing (!!!), use list2 or lst instead :

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

Though here the simplest is just to do :

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


来源:https://stackoverflow.com/questions/55396890/unquote-a-list-of-functions-inside-r-dplyr-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!