通过在使用 dplyr 的函数中使用非标准评估,寻找一种更有效/更优雅的方式将多个参数传递给组。我不想使用 ... 运算符,而是单独指定函数。
我的具体用例是一个函数,它接受一个数据框并创建一个语法更简单的 ggplot 对象。这是我想用我的函数自动化的代码示例:
# create data frame
my_df <- data.frame(month = sample(1:12, 1000, replace = T),
category = sample(head(letters, 3), 1000, replace = T),
approved = as.numeric(runif(1000) < 0.5))
my_df$converted <- my_df$approved * as.numeric(runif(1000) < 0.5)
my_df %>%
group_by(month, category) %>%
summarize(conversion_rate = sum(converted) / sum(approved)) %>%
ggplot + geom_line(aes(x = month, y = conversion_rate, group = category,
color = category))
我想将 group_by、summarize、ggplot 和 geom_line 组合成一个简单的函数,我可以提供 x、y 和组,并让它在后台执行所有肮脏的工作。这是我的工作:
# create the function that does the grouping and plotting
plot_lines <- function(df, x, y, group) {
x <- enquo(x)
group <- enquo(group)
group_bys <- quos(!! x, !! group)
df %>%
group_by(!!! group_bys) %>%
my_smry %>%
ggplot + geom_line(aes_(x = substitute(x), y = substitute(y),
group = substitute(group), color = substitute(group)))
}
# create a function to do the summarization
my_smry <- function(x) {
x %>%
summarize(conversion_rate = sum(converted) / sum(approved))
}
# use my function
my_df %>%
plot_lines(x = month, y = conversion_rate, group = category)
我觉得 group_by 处理非常不优雅:引用x
和group
with enquo
,然后!!
在另一个引用函数内部取消引用它们quos
,只是在下一行重新取消引用它们!!!
,但这是我唯一能够开始工作的事情. 有一个更好的方法吗?
另外,有没有办法让 ggplot!!
代替substitute
?我在做的事情感觉不一致。