Nic*_*abo 4 r lazy-evaluation ggplot2
我有一个问题,但在此解决方案中找不到答案。我的意思是,我想ggplot在新函数中使用该函数,例如
library(ggplot2)
draw_point <- function(data, x, y ){
ggplot(data, aes_string(x, y)) +
geom_point()
}
Run Code Online (Sandbox Code Playgroud)
结果我必须使用引号:
draw_point(mtcars, "wt", "qsec")
Run Code Online (Sandbox Code Playgroud)
相反,我想使用某种lazyeval包来编写这个不带引号的函数:
draw_point(mtcars, wt, qsec)
Run Code Online (Sandbox Code Playgroud)
有可能做到吗?
一种方法是使用substitute和aes_q。
draw_point <- function(data, x, y){
ggplot(data, aes_q(substitute(x), substitute(y))) +
geom_point()
}
draw_point(mtcars, wt, qsec)
Run Code Online (Sandbox Code Playgroud)
然而,如果你想要两者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)")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
419 次 |
| 最近记录: |