【发布时间】:2018-05-08 01:45:51
【问题描述】:
我在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 函数?
【问题讨论】:
-
df %>% group_by(Gender) %>% quick_pct_tab(get(col))函数内部似乎正在工作,但不确定是否能提供所需的输出