一种方法是使用substitute
和aes_q
。
draw_point <- function(data, x, y){
ggplot(data, aes_q(substitute(x), substitute(y))) +
geom_point()
}
draw_point(mtcars, wt, qsec)
但是,如果你想同时draw_point(mtcars, wt, qsec)
和draw_point(mtcars, "wt", "qsec")
工作,你必须更有创意一点。 以下是您可以使用lazyeval
软件包进行的初稿。这不能处理所有情况,但它应该让你开始。
draw_point <- function(data, x, y, ...){
# lazy x and y
ld <- as.lazy_dots(list(x = lazy(x), y = lazy(y)))
# combine with dots
ld <- c(ld, lazy_dots(...))
# change to names wherever possible
ld <- as.lazy_dots(lapply(ld, function(x){
try(x$expr <- as.name(x$expr), silent=TRUE)
x
}))
# create call
cl <- make_call(quote(aes), ld)
# ggplot command
ggplot(data, eval(cl$expr)) +
geom_point()
}
# examples that work
draw_point(mtcars, wt, qsec, col = factor(cyl))
draw_point(mtcars, "wt", "qsec")
draw_point(mtcars, wt, 'qsec', col = factor(cyl))
# examples that doesn't work
draw_point(mtcars, "wt", "qsec", col = "factor(cyl)")