4

I have a problem and I could not find the answer in this solution. I mean, I want to use the ggplot function within a new function, e.g.

library(ggplot2)
draw_point <- function(data, x, y ){
  ggplot(data, aes_string(x, y)) +
    geom_point()
}

and in result I have to use quotation marks:

draw_point(mtcars, "wt", "qsec")

Instead I want to use somehow lazyeval package to write this function without quotation marks:

draw_point(mtcars, wt, qsec)

It is possible to do it?

Community
  • 1
  • 1
Nicolabo
  • 1,337
  • 12
  • 30

1 Answers1

5

One way is to use substitute and aes_q.

draw_point <- function(data, x, y){
  ggplot(data, aes_q(substitute(x), substitute(y))) +
    geom_point()
}
draw_point(mtcars, wt, qsec)

However, if you want both draw_point(mtcars, wt, qsec) and draw_point(mtcars, "wt", "qsec") to work, you have to be a bit more creative. The following is a first draft of what you could do with the lazyeval package. This cannot handle all cases, but it should get you started.

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)")
shadow
  • 21,823
  • 4
  • 63
  • 77