我有一个问题,我在这个solution中找不到答案。我的意思是,我想在一个新的函数中使用ggplot函数。
library(ggplot2)
draw_point <- function(data, x, y ){
ggplot(data, aes_string(x, y)) +
geom_point()
}因此,我不得不使用引号:
draw_point(mtcars, "wt", "qsec")相反,我想以某种方式使用lazyeval包来编写这个函数,没有引号:
draw_point(mtcars, wt, qsec)这是可能的吗?
发布于 2015-03-03 09:31:19
一种方法是使用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)")https://stackoverflow.com/questions/28816684
复制相似问题