问题描述
我经常在包装函数中将 dplyr
与 ggplot2
结合进行分析。当我正在转向使用 tidyeval
的v.0.7.1的新NSE / SE范例时,我正在努力使这个组合发挥作用。我发现 ggplot
不理解未加引号的quosers(还)。以下不起作用:
example_func< - function(col){
col< - enquo(col )
mtcars%>%count(!! col)%>%
ggplot(aes((!! col),n))+
geom_bar(stat =identity)
example_func(cyl)
错误!col:无效参数类型
我目前使用以下解决方法。但我认为必须有更好的方法。
example_func2< - function(col){
col< - enquo(col)
mtcars%>%count(!! col)%>%
ggplot(aes_string(rlang :: quo_text(col),n))+
geom_bar(stat =identity)
}
请告诉我最好的方法结合这两者。如果您已经在处理问题,那么使用 aes _
接受以公式引用的输入: aes_(col,〜n)
。
这段代码解决了你的问题:
$ b $ pre $ library(tidyverse)
example_func< - function(col){
col< ; - enquo(col)
mtcars%>%count(!! col)%>%
ggplot(aes_(col,〜n))+
geom_bar(stat =identity )
}
example_func(cyl)
I often combine dplyr
with ggplot2
in wrapper functions for analysis. As I am moving to the new NSE / SE paradigm of v.0.7.1 with tidyeval
, I am struggling to get this combination to work. I found that ggplot
does not understand unquoted quosers (yet). The following does not work:
example_func <- function(col) {
col <- enquo(col)
mtcars %>% count(!!col) %>%
ggplot(aes((!!col), n)) +
geom_bar(stat = "identity")
}
example_func(cyl)
# Error in !col : invalid argument type
I currently use the following work-around. But I assume there must be a better way.
example_func2 <- function(col) {
col <- enquo(col)
mtcars %>% count(!!col) %>%
ggplot(aes_string(rlang::quo_text(col), "n")) +
geom_bar(stat = "identity")
}
Please show me what the best way to combine these two. Thanks!
If you are already handling quosures it's easier to use aes_
which accepts inputs quoted as a formula: aes_(col, ~n)
.
This bit of code solves your problem:
library(tidyverse)
example_func <- function(col) {
col <- enquo(col)
mtcars %>% count(!!col) %>%
ggplot(aes_(col, ~n)) +
geom_bar(stat = "identity")
}
example_func(cyl)
这篇关于用gpplot2使用dplyr SE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!