Bill Raynor
Bill Raynor

Reputation: 433

passing varying columns to aes inside a function

I am trying to write a function that calls ggplot with varying arguments to the 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 is the varying argument (I have multiple means). Following various posts here I have tried

  1. passing the column name quoted and unquoted (which yieds either an "unexpected string constant" or the "object not found error)
  2. setting up a local ennvironment (foo <-environment() followed by a environment= arg in ggplot)
  3. creating a new copy of the data set using a data2$column <- data[,column]

None of these appear to work within ggplot. How do I write a function that works? I will be calling it with different data.frames and columns:

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

Upvotes: 1

Views: 341

Answers (3)

Bill Raynor
Bill Raynor

Reputation: 433

I eventually got it to work with an aes_string() call: aes_string(x=foo, y=y, colour=color), wehre y and color were also defined externally to ggplot().

Upvotes: -1

ROLO
ROLO

Reputation: 4223

You example is not reproducible, but likely this will work:

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")

If you need more arguments to aes, do like this:

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

Upvotes: 2

Josh Gilfillan
Josh Gilfillan

Reputation: 5146

You could try this:

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")

Upvotes: 1

Related Questions