问题描述
我对如何将函数参数传递给dplyr和ggplot代码感到困惑.我正在使用dplyr和ggplot2的最新版本这是我的代码,用于生成条形图(清晰度与平均价格)
I'm confused about how to pass function argument into dplyr and ggplot codes.I'm using the newest version of dplyr and ggplot2Here is my code to produce a barplot (clarity vs mean price)
diamond.plot<- function (data, group, metric) {
group<- quo(group)
metric<- quo(metric)
data() %>% group_by(!! group) %>%
summarise(price=mean(!! metric)) %>%
ggplot(aes(x=!! group,y=price))+
geom_bar(stat='identity')
}
diamond.plot(diamonds, group='clarity', metric='price')
错误:
Error in UseMethod("group_by_") : no applicable method for 'group_by_' applied to an object of class "packageIQR"
对于最新版本的dplyr,不建议使用带下划线的verbs_().看来我们应该使用quasures.
For the newest version of dplyr, the underscored verbs_() is softly deprecated. It seems like we should use quosures.
我的问题:
- 有人可以澄清当前的最佳做法吗?
-
以上代码出了什么问题? (请不要下划线dplyr动词.)
- Can someone clarify the current best practice for this?
what was wrong with the above code? (no underscore dplyr verbs please..)
在ggplot中,我知道我们可以使用aes_string(),但就我而言,只有aes中的一个参数是通过函数参数传递的.
In ggplot, I know we can use aes_string(), but in my case, only one of the parameter in the aes is passed from function argument.
谢谢.
推荐答案
ggplot2 v3.0.0
,因此不再需要使用aes_
或aes_string
.
library(rlang)
library(tidyverse)
diamond_plot <- function (data, group, metric) {
quo_group <- sym(group)
quo_metric <- sym(metric)
data %>%
group_by(!! quo_group) %>%
summarise(price = mean(!! quo_metric)) %>%
ggplot(aes(x = !! quo_group, y = !! quo_metric)) +
geom_col()
}
diamond_plot(diamonds, "clarity", "price")
由 reprex软件包(v0.2.0)创建于2018-04-16.
Created on 2018-04-16 by the reprex package (v0.2.0).
这篇关于将函数参数传递给dplyr和ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!