-1

I have the following wrapper function:

plot.histogram = function(x.var, y.var, pf) {
  ggplot(aes_string(x.var, y.var), data = pf) +
    geom_bar(stat="identity", color = "black", fill = "steelblue") 
} 

The function works fine. However, sometimes I don't want to pass y.var and just use the default count on the y-axis. Thus, in that specific case, the chart shouldn't be a bar chart but a histogram. So depending on the absence of y.var, the function should automatically decide if it draws a bar chart or a histogram.

So, how can I make the parameter y.var optional and automatically have a histogram drawn if y.varis not given?

Amir Rahbaran
  • 2,380
  • 2
  • 21
  • 28
  • Reproducible example, please. And barplot != histogram, which do you want? – AkselA Jun 11 '17 at 12:22
  • You're absolutely right. Edited it: The question distinguishes now between bar chart and histogram. I didn't add a reproducible example to keep it short for the reader. It was more a functional / logical issue. – Amir Rahbaran Jun 11 '17 at 12:40

1 Answers1

1

If you are set on keeping the current parameters, I would set the y.var to have an initial value of NA then just pass it on. After initially setting an object p you can simply pass the y.var parameter later on:

plot.histogram = function(x.var, y.var = NA, pf) {
  p = ggplot(aes_string(x.var), data = pf)
  if(is.na(y.var) == TRUE){
    p + geom_histogram()
  }  
  else{
    p + geom_bar(aes_string(y = y.var),stat="identity", color = "black", fill = "steelblue")
  }
}
Scott Stoltzman
  • 363
  • 1
  • 15