原因
如果我们看一下aes源码,我们可以发现第一和第二个位置是被x和y保留的
> ggplot2::aes
function (x, y, ...)
{
exprs <- enquos(x = x, y = y, ..., .ignore_empty = "all")
aes <- new_aes(exprs, env = parent.frame())
rename_aes(aes)
}
让我们定义一个函数,看看它将如何影响aes():
testaes <- function(aesthetic, var){
aesthetic <- enquo(aesthetic)
var <- enquo(var)
print("with x and y:")
print(aes(Sepal.Length,Sepal.Width,!!(aesthetic) := !!var))
print("without x and y:")
print(aes(!!(aesthetic) := !!var))
}
> testaes(size, Petal.Width)
[1] "with x and y:"
Aesthetic mapping:
* `x` -> `Sepal.Length`
* `y` -> `Sepal.Width`
* `size` -> `Petal.Width`
[1] "without x and y:"
Aesthetic mapping:
* `x` -> ``:=`(size, Petal.Width)`
如您所见,当使用不带 x 和 y 的 := 时,aesthetic 和 var 被分配给 x。
为了系统地解决这个问题,需要更多关于 NSE 和 ggplot2 源代码的知识。
解决方法
始终将值分配给第一和第二位
library(ggplot2)
myfct <- function(aesthetic, var){
aesthetic <- enquo(aesthetic)
var <- enquo(var)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(x = Sepal.Length, y = Sepal.Width,!! (aesthetic) := !!var))
}
myfct(size, Petal.Width)
或者在 aes 上写一个包装器
library(ggplot2)
myfct <- function(aesthetic, var){
aesthetic <- enquo(aesthetic)
var <- enquo(var)
# wrapper on aes
myaes <- function(aesthetic, var){
aes(x = Sepal.Length, y = Sepal.Width,!! (aesthetic) := !!var)
}
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(mapping = myaes(aesthetic,var))
}
myfct(size, Petal.Width)
或者修改源代码
由于 x 和 y 是原因,我们可以通过删除 x 和 y 来修改 aes() 源代码。因为geom_*()通过默认inherit.aes = TRUE继承aes,所以你应该可以运行它。
aes_custom <- function(...){
exprs <- enquos(..., .ignore_empty = "all")
aes <- ggplot2:::new_aes(exprs, env = parent.frame())
ggplot2:::rename_aes(aes)
}
myfct <- function(aesthetic, var){
aesthetic <- enquo(aesthetic)
var <- enquo(var)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes_custom(!!(aesthetic) := !!var))
}
myfct(size, Petal.Width)
更新
简而言之,参数顺序很重要。使用 NSE 时,我们应该始终将 !!x := !!y 放在未命名参数的位置(例如 ...),而永远不要放在命名参数的位置。
我能够在 ggplot 之外重现该问题,因此根本原因来自 NSE。似乎:= 仅在处于未命名参数(...)的位置时才有效。在命名参数的位置(在以下示例中为x)时,它不会被正确评估。
library(rlang)
# test funciton
testNSE <- function(x,...){
exprs <- enquos(x = x, ...)
print(exprs)
}
# test data
a = quo(size)
b = quo(Sepal.Width)
:= 用于代替未命名的参数(...)
正常工作
> testNSE(x,!!a := !!b)
<list_of<quosure>>
$x
<quosure>
expr: ^x
env: global
$size
<quosure>
expr: ^Sepal.Width
env: global
:= 用于代替命名参数
它不起作用,因为!!a := !!b 用于testNSE() 的第一个位置,并且第一个位置已经具有名称x。因此它尝试将size := Sepal.Width 分配给x,而不是将Sepal.Width 分配给size。
> testNSE(!!a := !!b)
<list_of<quosure>>
$x
<quosure>
expr: ^^size := ^Sepal.Width
env: global