[Rd] Problems caused by dev.off() behaviour

Trevor Davis trevor@|@d@v|@ @end|ng |rom gm@||@com
Mon Oct 2 22:21:46 CEST 2023


> Use it just like dev.off(), but it *will* restore the previous device.

I'm observing that if there were no previously open graphics devices then
your `safe.dev.off()` opens up a new graphics device which may be an
undesired side effect (because "surprisingly" `dev.set()` on the null
graphics device opens up a new graphics device).  To avoid that you could
check if `dev.list()` is greater than length 1L:

   safe.dev.off  <- function(which = dev.cur(), prev = dev.prev()) {
     force(prev)
     dev.off(which)
     if (length(dev.list()) > 1L) {
       dev.set(prev)
     }
   }

Trevor

On Mon, Oct 2, 2023 at 11:54 AM Duncan Murdoch <murdoch.duncan using gmail.com>
wrote:

> I found some weird behaviour and reported it as
> https://bugs.r-project.org/show_bug.cgi?id=18604 and
> https://github.com/yihui/knitr/issues/2297, but it turns out it was user
> error.
>
> The dev.off() function was behaving as documented, but it behaves in an
> unexpected (by me) way, and that caused the "bugs".
>
> The issue is that
>
>     dev.off()
>
> doesn't always result in the previous graphics device being made
> current.  If there are two or more other open graphics devices, it won't
> choose the previous one, it will choose the next one.
>
> I'm letting people know because this might affect other people too.  If
> you use dev.off(), don't assume it restores the previous device!
>
> Here's my little workaround alternative:
>
>    safe.dev.off  <- function(which = dev.cur(), prev = dev.prev()) {
>      force(prev)
>      dev.off(which)
>      dev.set(prev)
>    }
>
> Use it just like dev.off(), but it *will* restore the previous device.
>
> Duncan Murdoch
>
> ______________________________________________
> R-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>

	[[alternative HTML version deleted]]



More information about the R-devel mailing list