Reputation: 60492
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
Upvotes: 7
Views: 269
Reputation: 103938
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()
.
Upvotes: 20
Reputation: 23758
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?
Upvotes: 0