r - ggplot2 中的lazyeval 在其他函数中

标签 r ggplot2 lazy-evaluation

我有一个问题,我在这个 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)

有可能做到吗?

最佳答案

一种方法是使用 substituteaes_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)")

关于r - ggplot2 中的lazyeval 在其他函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28816684/

相关文章:

R - 为列表中的每个数据帧添加新 ID(使用 apply 或 dplyr)

scala - Scala 中的惰性求值、thunk 和函数闭包

python - csv 数据可以变得懒惰吗?

r - 在 for 循环中包含变量

r - 按钮 : download button with scroller downloads only few rows

r - 累积列总和以通知 R 中的另一个列值

r - 在月轴上准确放置 geom_text 标签

R ggplot facet_wrap 具有不同的 y 轴标签,一个值,一个百分比

r - 如何向 ggplot + geom_point 图中添加均值

r - 如何使用 GGPLOT 创建分面相关图