1

If a function draws a graph inside the function using plot and also returns an invisible object, how do I only keep the object and not display the plot?

some_func <- function() {
  plot(1:10)
  return(invisible(10))
}

my_value <- some_func() # R/Rstudio draws a plot! don't want that
lmo
  • 37,904
  • 9
  • 56
  • 69
Alby
  • 5,522
  • 7
  • 41
  • 51

1 Answers1

4

I'm not sure why you are doing this, presumably you wish to call plot only for some side effect. Usually this would be the case if you are interested in getting a return value from the plot function, for example using boxplot to calculate the statistics.

With some plot methods, there is an argument plot = FALSE you can use. for example with boxplots you can specify boxplot(..., plot = FALSE).

But this does not work with the basic plot function. Other options are to use a different plotting library, such as lattice or ggplot, that allow you to assign a plot to an object, rather than draw it. But if you really need to do this with base plot, then the only way I can think of is to send the output to a device other than your screen. For example, to send the output to a temporary .png file and then delete the file, you can do

some_func <- function() {
  png("temp.xyz")
  a=plot(1:10, )
  dev.off()
  file.remove("temp.xyz")
  return(invisible(10))
}

my_value <- some_func()
dww
  • 30,425
  • 5
  • 68
  • 111