2015-03-02 125 views
3

我有一個問題,我找不到在這solution答案。我的意思是,我想在一個新功能中使用ggplot函數,例如ggplot2 lazyeval其他功能

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) 

有可能去做吧?

回答

4

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