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

2024-01-04

我编写了一个简单的函数来创建百分比表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) and enquo(col), etc.

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

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

Update

with 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 dplyr 通过多个函数传递列名 的相关文章

随机推荐