我正在寻找增加大型数据集数据效率的方法。为此,我使用ggplot2创建了几个函数。由此产生的一些数字可能是用于分发的,因此,我希望它们具有易于理解的标题和轴标签。我在想我可以使用将标签关联到每个变量attr()
。这样,我不必重命名变量并处理包含空格的长变量名。使用ggplot的函数时,我已成功完成此任务
library(ggplot2)
library(magrittr)
# Set attributes
mt <- mtcars
attr(mt$mpg, "desc") <- "Miles per Gallon"
attr(mt$cyl, "desc") <- "Number of Cylinders"
mt %>%
ggplot() +
geom_point(aes(x = cyl, y = mpg)) +
labs(x = attr(mt$cyl, "desc"),
y = attr(mt$mpg, "desc"))
上面的代码行为符合我的期望,并返回包含轴标签的图形。但是,当我创建图形功能时,我无法弄清楚如何访问变量属性。以下两个尝试均成功创建了图形,但是未生成轴标签
vis_1 <- function(.data, .x, .y) {
.data %>%
ggplot() +
geom_point(aes(x = {{.x}}, y = {{.y}})) +
labs(x = attr({{.data$.x}}, "desc"),
y = attr({{.data$.y}}, "desc"))
}
vis_1(.data = mt, .x = cyl, .y = mpg)
和
vis_2 <- function(.data, .x, .y) {
attr_x <- attr(.data$.x, "desc")
attr_y <- attr(.data$.y, "desc")
.data %>%
ggplot() +
geom_point(aes(x = {{.x}}, y = {{.y}})) +
labs(x = attr_x,
y = attr_y)
}
vis_2(.data = mt, .x = cyl, .y = mpg)
任何建议,将不胜感激。
这里的问题是引用您传递的变量。
如果您愿意使用cyl
和mpg
作为引用变量,则是一种选择。中的基本[
子集attr
可以正常工作,ggplot
您可以使用!!sym()
。
vis_2 <- function(df, x, y) {
attr_x <- attr(df[,x], "desc")
attr_y <- attr(df[,y], "desc")
df %>%
ggplot() +
geom_point(aes(!!sym(x), !!sym(y))) +
labs(x = attr_x,
y = attr_y)
}
vis_2(mt, 'cyl', 'mpg')
传递未加引号的变量的版本。此解决方案deparse(substitute(x))
用于[
呼叫中和!!enquo(x)
用于中ggplot
。
vis_3 <- function(df, x, y) {
# base quoting
x_sub <- deparse(substitute(x))
y_sub <- deparse(substitute(y))
attr_x <- attr(df[,x_sub], "desc")
attr_y <- attr(df[,y_sub], "desc")
df %>%
ggplot() +
geom_point(aes(!!enquo(x), !!enquo(y))) +
labs(x = attr_x,
y = attr_y)
}
vis_3(mt, cyl, mpg)
另一个版本使用了无引号的变量,该版本使用{{
forggplot
和deparse(ensym()
for [
。
vis_4 <- function(df, x, y) {
attr_x <- attr(df[,deparse(ensym(x))], "desc")
attr_y <- attr(df[,deparse(ensym(y))], "desc")
df %>%
ggplot() +
geom_point(aes({{x}}, {{y}})) +
labs(x = attr_x,
y = attr_y)
}
vis_4(mt, cyl, mpg)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句