【问题标题】:lazyeval in ggplot2 within other function其他函数中的 ggplot2 中的lazyeval
【发布时间】:2015-03-02 18:16:16
【问题描述】:

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

有可能吗?

【问题讨论】:

    标签: r ggplot2 lazy-evaluation


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2016-06-18
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      相关资源
      最近更新 更多