【发布时间】:2021-08-14 02:56:45
【问题描述】:
以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 是的,错字。我将编辑问题。