r - 在自定义函数中将列名传递给 group_by 和 ggplot2
问题描述
我的数据框有多个分类列,我想将每一列与固定列进行比较并生成条形图facet_grid()
。为此,我想编写一个函数。
library(rlang)
library(tidyverse)
qw <- structure(list(weekday = structure(c(2L, 6L, 7L, 5L, 1L, 3L,
4L, 2L, 6L, 7L, 5L, 1L, 3L, 4L, 2L, 6L, 7L, 5L, 1L, 3L, 4L, 2L,
6L, 7L, 5L, 1L, 3L, 4L, 2L, 6L, 7L, 5L, 1L, 3L, 4L), .Label = c("Friday",
"Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"
), class = "factor"), Target = c(0, 0, 1, 1, 0, 1, 1, 1, 1, 0,
0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0,
1, 0, 0, 1), type = structure(c(3L, 3L, 2L, 3L, 1L, 3L, 1L, 3L,
1L, 1L, 3L, 2L, 1L, 3L, 3L, 1L, 3L, 1L, 2L, 2L, 2L, 2L, 1L, 1L,
1L, 3L, 2L, 1L, 2L, 1L, 2L, 1L, 3L, 2L, 3L), .Label = c("Advertising",
"Agriculture", "Bank"), class = "factor")), .Names = c("weekday",
"Target", "type"), row.names = c(NA, -35L), class = "data.frame")
qw %>%
group_by(type, Target) %>%
summarise(Freq = n()) %>%
ggplot(data = ., aes(x = reorder(type, -Freq), y = Freq, fill = type)) +
geom_bar(stat = 'identity') +
labs(y = "", x = "") +
facet_grid(Target ~ ., scales = "free") +
theme(legend.position = 'none')
这里Target列是固定的 group_by()
和facet_grid()
函数。以类似的方式,我想与多列进行比较。
为此我写了一个函数
cateby_label_graph <- function(x){
x <- syms(x)
qw %>%
group_by(!!!x, Target) %>%
summarise(Freq = n()) %>%
ggplot(data = . , aes(x = reorder(x, -Freq), y = Freq, fill = x)) +
geom_bar(stat = 'identity') +
labs(y = "", x = "") +
facet_grid(Target~., scales="free") +
theme(legend.position = 'none')
}
上述功能group_by()
在收到错误之前正在工作。
解决方案
您想要sym
(not syms
) 并且需要在通话中取消引用x
using!!
ggplot
# Need ggplot2 3.0.0 to use tidy evaluation in ggplot2
# install.packages("ggplot2", dependencies = TRUE)
library(rlang)
library(tidyverse)
cateby_label_graph2 <- function(df, x) {
x <- sym(x)
df %>%
group_by(!! x, Target) %>%
summarise(Freq = n()) %>%
ggplot(data = ., aes(x = reorder(!! x, -Freq), y = Freq, fill = !! x)) +
geom_col() +
labs(y = "", x = "") +
facet_grid(Target ~ ., scales = "free") +
theme(legend.position = 'none')
}
cateby_label_graph2(qw, 'type')
由reprex 包(v0.2.0.9000)于 2018 年 7 月 2 日创建。
推荐阅读
- python - 为什么我会收到“IndentationError:预期有缩进块”
- java - 如何将 ConcurrentWebSocketSessionDecorator 与自定义 WebSocketHandler 一起使用
- java - java串行和并行流的多次传递与单次传递数据
- python - 使用 sci-kit 学习的多类多输出回归
- arrays - 我可以简化这个数组的创建吗?
- javascript - 从页面正文显示数据到模态正文
- sql-server - 如何使用 SSIS 将 SQL db 连接/链接到 Access 数据库?
- javascript - Sheetjs`!rows`(和`!cols`)属性在新创建的工作表上不存在?
- python - Matplotlib:辅助轴与两个主轴共享值
- ios - 删除 UItableView Cell 的第一行分隔符