如何创建一个函数来改变具有变量名和“_pct”的新列?
mtcars作为例子使用。我想编写一个创建函数count和pct列,如下面-
library(tidyverse)
mtcars %>%
group_by(cyl) %>%
summarise(count = n()) %>%
ungroup() %>%
mutate(cyl_pct = count/sum(count))
这会产生输出 -
# A tibble: 3 x 3
cyl count mpg_pct
<dbl> <int> <dbl>
1 4 11 0.344
2 6 7 0.219
3 8 14 0.438
但是,我想创建一个函数,在该函数中我可以将group_by列指定为任何列,并且该mutate列将命名groub_by为_pct. 因此,如果我想使用disp,disp将是我的group_by变量,并且该函数将改变一disp_pct列。
回答
类似于 akrun 的答案,但使用{{代替!!:
foo = function(data, col) {
data %>%
group_by({{col}}) %>%
summarize(count = n()) %>%
ungroup %>%
mutate(
"{{col}}_pct" := count / sum(count)
)
}
foo(mtcars, cyl)
# `summarise()` ungrouping output (override with `.groups` argument)
# # A tibble: 3 x 3
# cyl count cyl_pct
# <dbl> <int> <dbl>
# 1 4 11 0.344
# 2 6 7 0.219
# 3 8 14 0.438