我正在尝试创建一个用于使用ggplot2
创建棒棒糖图的函数。我想将...
中的所有参数传递给aes()
中的geom_point()
。但是,我想从size
内的aes()
传递中排除geom_segment()
参数(出于显而易见的原因,如果您查看下面的a()
的输出)。因此,我使用...
捕获了rlang::enquos()
,而不是照原样传递。在我将a()
内的dots
传递给aes()
的函数ggplot()
中,此方法没有问题。但是在函数b()
中出现错误Can't use '!!!' at top level.
我现在处于困顿状态,不胜感激,希望为解决此问题提供任何投入。
library(ggplot2)
data("mtcars")
d <- dplyr::count(mtcars, cyl, am)
a <- function(data, x, y, ...) {
x <- rlang::enquo(x)
y <- rlang::enquo(y)
dots <- rlang::enquos(...)
ggplot(data, aes(!!x, !!y, !!!dots)) +
geom_segment(aes(y = 0, xend = !!x, yend = !!y)) +
geom_point()
}
b <- function(data, x, y, ...) {
x <- rlang::enquo(x)
y <- rlang::enquo(y)
dots <- rlang::enquos(...)
segment_args <- dots[names(dots) != "size"]
ggplot(data, aes(!!x, !!y)) +
geom_segment(aes(y = 0, xend = !!x, yend = !!y, !!!segment_args)) +
geom_point(aes(!!!dots))
}
a(d, cyl, n, color = factor(am), size = am)
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLmltZ3VyLmNvbS8xNjk4MDhNLnBuZyJ9” alt =“”>
b(d, cyl, n, color = factor(am), size = am)
#> Error: Can't use `!!!` at top level.
这里是我的sessionInfo()
:
R version 3.5.2 (2018-12-20)
Platform: x86_64-apple-darwin16.7.0 (64-bit)
Running under: macOS Sierra 10.12.1
Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /usr/local/Cellar/openblas/0.3.5/lib/libopenblasp-r0.3.5.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods
[7] base
other attached packages:
[1] ggplot2_3.2.1
loaded via a namespace (and not attached):
[1] Rcpp_1.0.3 digest_0.6.18 withr_2.1.2
[4] assertthat_0.2.0 crayon_1.3.4 dplyr_0.8.3
[7] grid_3.5.2 R6_2.3.0 gtable_0.2.0
[10] magrittr_1.5 scales_1.0.0 pillar_1.4.2
[13] rlang_0.4.2 lazyeval_0.2.1 rstudioapi_0.10
[16] labeling_0.3 tools_3.5.2 glue_1.3.0
[19] purrr_0.3.3 munsell_0.5.0 compiler_3.5.2
[22] pkgconfig_2.0.2 colorspace_1.4-0 tidyselect_0.2.5
[25] tibble_2.1.3
我认为您不再需要引用/取消引用。相反,您可以使用双括号{{ x }}
,并将点保留为点...
以下工作原理,而且更容易理解:
b <- function(data, x, y, ...) {
ggplot(data, aes( {{x}} , {{y}} )) +
geom_segment(aes(y = 0, xend = {{x}}, yend = {{y}}, ...)) +
geom_point(aes(...))
}