r - 使用 dplyr 通过多个函数传递列名

标签 r dplyr tidyverse

我编写了一个简单的函数来创建 dplyr 中的百分比表:

library(dplyr)

df = tibble(
    Gender = sample(c("Male", "Female"), 100, replace = TRUE),
    FavColour = sample(c("Red", "Blue"), 100, replace = TRUE)
)

quick_pct_tab = function(df, col) {
    col_quo = enquo(col)
    df %>%
        count(!! col_quo) %>%
        mutate(Percent = (100 * n / sum(n)))
}

df %>% quick_pct_tab(FavColour)
# Output:
# A tibble: 2 x 3
  FavColour     n Percent
      <chr> <int>   <dbl>
1      Blue    58      58
2       Red    42      42

这很好用。然而,当我尝试在此基础上构建时,编写一个通过分组计算相同百分比的新函数,我无法弄清楚如何使用 quick_pct_tab在新功能中 - 在尝试 quo(col) 的多种不同组合之后, !! quo(col)enquo(col)

bygender_tab = function(df, col) {
    col_enquo = enquo(col)
    # Want to replace this with 
    #   df %>% quick_pct_tab(col)
    gender_tab = df %>%
        group_by(Gender) %>%
        count(!! col_enquo) %>%
        mutate(Percent = (100 * n / sum(n)))

    gender_tab %>%
        select(!! col_enquo, Gender, Percent) %>%
        spread(Gender, Percent)
}
> df %>% bygender_tab(FavColour)
# A tibble: 2 x 3
  FavColour   Female     Male
*     <chr>    <dbl>    <dbl>
1      Blue 52.08333 63.46154
2       Red 47.91667 36.53846

据我了解dplyr中的非标准评估已弃用,因此学习如何使用 dplyr > 0.7 来实现这一点会很棒。我该如何引用 col将其传递给进一步的参数 dplyr功能?

最佳答案

我们需要执行 !! 来触发“col_enquo”的评估

bygender_tab = function(df, col) {
   col_enquo = enquo(col)

   df %>% 
      group_by(Gender) %>%
      quick_pct_tab(!!col_enquo)  %>%  ## change
      select(!! col_enquo, Gender, Percent) %>%
      spread(Gender, Percent)   
}

df %>% 
    bygender_tab(FavColour)
# A tibble: 2 x 3
#   FavColour   Female     Male
#*     <chr>    <dbl>    <dbl>
#1      Blue 54.54545 41.07143
#2       Red 45.45455 58.92857

使用OP的函数,输出为

# A tibble: 2 x 3
#  FavColour   Female     Male
#*     <chr>    <dbl>    <dbl>
#1      Blue 54.54545 41.07143
#2       Red 45.45455 58.92857

请注意,创建数据集时未设置种子

更新

使用rlang版本0.4.0(使用dplyr - 0.8.2运行),我们还可以使用 {{...}} 进行引用、取消引用、替换

bygender_tabN = function(df, col) {
  

    df %>% 
       group_by(Gender) %>%
       quick_pct_tab({{col}})  %>%  ## change
       select({{col}}, Gender, Percent) %>%
       spread(Gender, Percent)   
 }
 
df %>% 
     bygender_tabN(FavColour)
# A tibble: 2 x 3
#  FavColour Female  Male
#  <chr>      <dbl> <dbl>
#1 Blue          50  46.3
#2 Red           50  53.7
     

-使用之前的函数检查输出(未提供 set.seed)

df %>% 
     bygender_tab(FavColour)
# A tibble: 2 x 3
#  FavColour Female  Male
#  <chr>      <dbl> <dbl>
#1 Blue          50  46.3
#2 Red           50  53.7

关于r - 使用 dplyr 通过多个函数传递列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466577/

相关文章:

r - 如何在排序和删除元素后恢复向量的原始顺序?

r - 为什么 dplyr 无法按行生成结果?

r - 如何使用管道 (%>%) 运算符正确地使 vim 缩进 dplyr 代码?

r - 如何在保留非数字列的同时删除总和为 0 的列和行

r - 在 tidyverse 中不中断管道的情况下打印中间结果

基于两列删除重复项,在第三列保留一个具有较大值的列,同时保持所有列不变

r - 如何将列表列表转换为小标题(数据框)

r - 停止运行 Shiny 的应用程序键盘快捷键

r - 如何标记上周五或最后一天或上个月

r - 过滤具有重叠区域的行