tags:

views:

112

answers:

4

Is there a way to determine if a function generates a figure in R?

For example, if we have functions f and g

f = function(x,y){plot(x,y)}
g = function(x,y){mean(x*y)}

I would like able to run

createFigure(f(x,y))#Returns TRUE
createFigure(g(x,y))#Returns FALSE

Thanks

A: 

I think it is not possible for base graphics, since many plot.xx functions return "NULL". Maybe you could check .Device in your createFigure function to find out if the number of the open devices has changed. But this will not work in general as plot does not open a new device by default.

If you use ggplot2, you could check the class of the return value. Class "ggplot" indicates a graphic.

Karsten W.
A: 

If, for your purposes, it's OK to have all devices off before hand then checking .Devices would be fine because then plotting commands do make a new device. But then lines(), and points() would be exceptions.

In fact, this suggests that the question doesn't just have a true or false answer but depends on conditions. Some functions will draw something even if there is no open device while others will draw something if there is something else drawn. What would you want to do in that case?

John
I have a Sweave document that calls the function. If a graph is created I include it in the Tex file.The functions come from students.
csgillespie
+16  A: 
makes_plot <- function(x) {
  before <- .Internal(getSnapshot())
  force(x)
  after <- .Internal(getSnapshot())
  !identical(before, after)
}

makes_plot(mean(1:10))
makes_plot(plot(1:10))

The .getSnapshot function was discovered by looking at the source of recordPlot().

hadley
Very nicely done!
Dirk Eddelbuettel
+1 Maybe include that in ggplot2 so that it's readily available?
Shane
Nice! (fulfilling min(length(comment))
Dan
A: 

maybe http://goo.gl/JMfm

Rick
For those who don't use unknown link - it's a package `hints` http://cran.r-project.org/web/packages/hints/index.html
Marek