2

I have a function:

MakeTxHistogram <-function(d,x,plot.labels) {
  print(dim(d))
  ggplot(data=d) +
    geom_histogram(aes_string(x=x,y="..density..",fill="var1")) + 
    scale_x_log10() + facet_grid( var1~ var2 ) +  labs(title=plot.labels[1],x=plot.labels[2]) +
    theme
}

MakeTxHistogram does exactly what I want when called directly from a script or the console. So I created a new function:

TestAndPlot<-function() {
 MakeTxHistogram(d1,x,plot.labels)
 MakeTxHistogram(d2,x,plot.labels)
 RunAStatisticalTest()
}

When I call TestAndPlot(), then both calls of MakeTxHistogram(...) execute, but no plot is generated (the print() function works, however). If instead I write TestAndPlot as:

TestAndPlot<-function() {
 RunAStatisticalTest()
 MakeTxHistogram(d1,x1,plot.labels1)
 MakeTxHistogram(d2,x2,plot.labels2)
}

Then RunAStatisticalTest() works, the first call of MakeTxHistogram executes but does not generate a plot, and the second call of MakeTxHistogram executes and successfully generates the plot.

Have tried implementing solutions such as those suggested here, including setting the environment to the local environment, and (obviously) using aes_string() instead of aes(). Can anyone suggest the source of the problem and a possible solution? I can just go back to calling these functions directly, but would rather be able to nest them inside of something (or understand why I can't/shouldn't do that).

Thanks!

Community
  • 1
  • 1
Isaac
  • 101
  • 6
  • 4
    You need to `print()` your plots. Without an explicit `return()`, only the last object from a function is returned a printed implicitly. – MrFlick May 28 '15 at 19:05
  • It's essentially the same problem as here: http://stackoverflow.com/a/6675610/2372064 and part of the R FAQ list: http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f – MrFlick May 28 '15 at 19:06
  • That was exactly the problem. Thank you! – Isaac May 28 '15 at 19:09

0 Answers0