取消引用R dplyr函数中的函数列表 [英] unquote a list of functions inside R dplyr functions

查看:92
本文介绍了取消引用R dplyr函数中的函数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然后我将 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


推荐答案

list 不支持拼接( !!! ),使用 list2 lst 代替:

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

这篇关于取消引用R dplyr函数中的函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆