使用dplyr

时间:2017-11-24 04:54:09

标签: 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)组合之后1}},!! 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函数?

1 个答案:

答案 0 :(得分:2)

我们需要!!来触发评估&#39; col_enquo&#39;

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

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