You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Based on code I wrote a while ago to accomplish a similar thing, I'd like to suggest an actual with_dev function:
## Returns TRUE if x refers to the device number of a currently active## graphics device.
library(rlang)
library(assertthat)
is_dev<-function(x) {
is_scalar_integer(x) &&x%in% dev.list()
}
with_dev<-function(dev, code, closedev) {
orig.device<- dev.cur()
new.device<- force(dev)
# Functions that create devices don't generally return them, they# just set them as the new current device, so get the actual# device from dev.cur() instead.if (is.null(new.device)) {
new.device<- dev.cur()
}
assert_that(is_dev(new.device))
message(glue("Orig device: {deparse(orig.device)}; new device: {deparse(new.device)}"))
if (missing(closedev)) {
closedev<-new.device!=orig.device
}
on.exit({
if (closedev) {
dev.off(new.device)
}
if (is_dev(orig.device)) {
dev.set(orig.device)
}
})
force(code)
}
# Usage:
library(ggplot2)
with_dev(pdf(file.path(tempdir(), "test.pdf")), print(qplot(x=1:50, y=rnorm(50))))
The dev argument should either be code that returns a graphics device, or code that creates a new graphics device, sets it as the current device, and returns NULL. (Functions like png, pdf, etc. fall into the latter category.)
The function tries to auto-detect whether or not is should close the device when done with it. The heuristic is that if evaluating dev changes the value of dev.cur(), then the device will be closed on exit. This can be overridden with the closedev argument.
The is_dev function is just a helper here, but it might be worth including in rlang, named something like is_graphics_device.
Based on code I wrote a while ago to accomplish a similar thing, I'd like to suggest an actual
with_dev
function:The
dev
argument should either be code that returns a graphics device, or code that creates a new graphics device, sets it as the current device, and returns NULL. (Functions likepng
,pdf
, etc. fall into the latter category.)The function tries to auto-detect whether or not is should close the device when done with it. The heuristic is that if evaluating
dev
changes the value ofdev.cur()
, then the device will be closed on exit. This can be overridden with theclosedev
argument.The
is_dev
function is just a helper here, but it might be worth including in rlang, named something likeis_graphics_device
.My original code: https://github.com/DarwinAwardWinner/CD4-csaw/blob/master/scripts/utilities.R#L143-L169
The text was updated successfully, but these errors were encountered: