我经常在工作中使用ggplot2并构建包装函数以加快我的工作流程.使用非标准评估(NSE)aes迫使我使用实际的变量名而不是传递字符串.所以我复制并重命名数据帧和变量名以安抚ggplot2.必须有一个更好的方法.如何通过函数包装器使ggplot2接受未知的数据帧和列名,而无需复制数据帧和使用通用列名?
这有效:
ggplot(mtcars, aes(x=mpg, y=hp)) +
geom_point()
Run Code Online (Sandbox Code Playgroud)
这不是:
FUN <- function(dat, x, y) {
ggplot(dat, aes(x = x, y = y)) +
geom_point()
}
FUN(mtcars, "mpg", "hp")
Run Code Online (Sandbox Code Playgroud)
Tyl*_*ker 39
有一个aes_string功能,我没有真正看到突出,这正是这样做:
FUN <- function(dat, x, y) {
ggplot(dat, aes_string(x = x, y = y)) +
geom_point()
}
FUN(mtcars, "mpg", "hp")
Run Code Online (Sandbox Code Playgroud)
Ron*_*hah 19
现在建议使用.data代词
FUN <- function(dat, x, y) {
ggplot(dat, aes(x = .data[[x]], y = .data[[y]])) +
geom_point()
}
FUN(mtcars, "mpg", "hp")
Run Code Online (Sandbox Code Playgroud)
其他几个选择 -
#Using get
FUN <- function(dat, x, y) {
ggplot(dat, aes(x = get(x), y = get(y))) +
geom_point()
}
#Using sym
FUN <- function(dat, x, y) {
ggplot(dat, aes(x = !!sym(x), y = !!sym(y))) +
geom_point()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5997 次 |
| 最近记录: |