2016-01-08 26 views
3

我是新來編寫函數的,所以我一直無法弄清楚這一點可能並不奇怪。我只想生成一個簡單的函數,其中一個指定數據框和您想要的變量,然後ggplot生成一個二元圖。我覺得作爲下面我用建議的功能與GGPLOT2一對夫婦的解決辦法應該工作:使用ggplot2編寫一個簡單的函數

library(ggplot2) 

xy <- data.frame(xvar=1:10,yvar=1:10) 

plotfunc <- function(Data, x, y){ 
    .e <- environment() 
    ggplot(Data, aes(x = x, y = y), environment = .e) + 
    geom_line() 
} 

plotfunc(xy, xvar, yvar) 

然而,上面的代碼生成此錯誤消息:對我是什麼

Error in eval(expr, envir, enclos) : object 'xvar' not found 
In addition: Warning message: 
In eval(expr, envir, enclos) : restarting interrupted promise evaluation 

任何建議在這裏做錯了嗎?顯然這是一個微不足道的例子,我希望能夠將其擴展到更廣泛的用途。

在此先感謝。

回答

5

使用aes_q

plotfunc <- function(Data, x, y){ 
    print(
    ggplot(Data, aes_q(x = substitute(x), y = substitute(y))) + 
     geom_line() 
) 
} 

plotfunc(xy, xvar, yvar)