2

I have the following function that I'd like to use to generate density histograms of various features in a dataset:

fraudSplitHist <- function(dataframe, stat_col, signal_col='fraud') {
  hist_data <- dataframe[,c(stat_col, signal_col)]
  colnames(hist_data) <- c('stat', 'fraud')

  hist_data$stat <- winsor1(hist_data$stat) # remove outliers

  ggplot(hist_data, aes(hist_data$stat, fill=as.factor(hist_data$fraud))) +
    geom_histogram(alpha=0.5, aes(y=..density..), position='identity', binwidth=1)
}

Running it always give me this error

fraudSplitHist(dataframe=data, stat_col='some_column_of_values')
Error in eval(expr, envir, enclos) : object 'hist_data' not found

However, it works with qplot

fraudSplitHist <- function(dataframe, stat_col, fraud_col='fraud') {
  hist_data <- dataframe[,c(stat_col, fraud_col)]
  colnames(hist_data) <- c('stat', 'fraud')

  hist_data$stat <- winsor1(hist_data$stat)

  qplot(data=hist_data, x=stat, geom="histogram", fill=as.factor(fraud), binwidth=10,
        position='identity')
}

Any ideas what I could be missing here?

Tyler Wood
  • 1,947
  • 2
  • 19
  • 29
  • 2
    Questions like this are much easier to answer if you actually provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) complete with sample data so we can copy/paste into R and re-create the problem. – MrFlick Oct 08 '14 at 19:43
  • 5
    You should never, ever, be using `$` to select columns inside of `aes()`. See `?aes_string`. – joran Oct 08 '14 at 19:44

1 Answers1

3

You should not specify the data.frame name in your aes() settings. You should be just using column names from the data.frame. For example, this should work

simpletest <- function(dataframe, x_col, y_col='cyl') {
  plot_data <- dataframe[,c(x_col, y_col)]
  colnames(plot_data) <- c('stat', 'fraud')

   ggplot(plot_data, aes(stat, fill=as.factor(fraud))) +
    geom_histogram(alpha=0.5, aes(y=..density..), position='identity', binwidth=1)
}

simpletest(mtcars, "disp")
MrFlick
  • 195,160
  • 17
  • 277
  • 295