2014-07-10 112 views
1

我想寫的是具有可變參數的AES調用ggplot一個函數裏面AES列:通過不同的功能

hmean <- function(data, column, Label=label){ 
    ggplot(data,aes(column)) + 
    geom_histogram() + 
    facet_wrap(~Antibody,ncol=2) + 
    ggtitle(paste("Mean Antibody Counts (Log2) for ",Label," stain")) 
} 
hmean(Log2Means,Primary.Mean, Label="Primary") 
Error in eval(expr, envir, enclos) : object 'column' not found 

Primary.Mean是變化的參數(我有多個手段)。在此之後各個崗位我都試過

  1. 通過列名報價,不需要加引號(其中yieds無論是「令人驚喜的字符串常量」或「找不到對象錯誤)
  2. 建立一個本地ennvironment(foo <-environment()其次在ggplot一個environment= ARG)
  3. 使用它們的data2$column <- data[,column]

無創建數據集的新副本出現ggplot內工作。我怎麼寫的作品?功能我會用不同的data.frames和列稱之爲:

hmean(Log2Means, Primary.mean, Label="Primary") 
hmean(Log2Means, Secondary.mean, Label="Secondary") 
hmean(SomeOtherFrame, SomeColumn, Label="Pretty Label") 
+0

有沒有任何答案對您有幫助?如果是這樣,不要忘記接受:https://stackoverflow.com/help/someone-answers – ROLO

回答

1

你可以試試這個:

hmean <- function(data, column, Label=label){ 

    # cool trick? 
    data$pColumn <- data[, column] 

    ggplot(data,aes(pColumn)) + 
    geom_histogram() + 
    facet_wrap(~Antibody,ncol=2) + 
    ggtitle(paste("Mean Antibody Counts (Log2) for ",Label," stain")) 
} 
hmean(Log2Means,'Primary.Mean', Label="Primary") 
2

您的例子並不reproducible,但很可能這將工作:

hmean <- function(data, column, Label=label){ 
    ggplot(data, do.call("aes", list(y = substitute(column)))) + 
     geom_histogram() + 
     facet_wrap(~Antibody,ncol=2) + 
     ggtitle(paste("Mean Antibody Counts (Log2) for ",Label," stain")) 
} 

hmean(Log2Means,Primary.Mean, Label="Primary") 

如果您需要更多參數到aes,請這樣做:

do.call("aes", list(y = substitute(function_parameter), x = quote(literal_parameter))) 
-1

我最終得到它與aes_string()調用:aes_string(x=foo, y=y, colour=color),我們ycolor也被定義爲外部ggplot()