Richie Cotton
Richie Cotton

Reputation: 121077

How to get the file associated with a graphics device?

While printing a plot to a file, I want to find the location of the file that I'm printing to.

pdf("test.pdf")
plot(1:5)
# Somehow retrieve "test.pdf"
dev.off()

In this example, I specified the filename when I called pdf so the answer is obvious. My use case is when the file location has been automatically generated, for example in a knitr document.

For file connections, you can get the associated file using summary(conn)$description. I was hoping to be able to get something useful from summary(dev.cur()) or str(dev.cur()), but no luck there.

How can I go from dev.cur() to the associated file? Alternatively, how can I retrieve the location of the file that the plot is being written to?

Upvotes: 4

Views: 99

Answers (1)

nicola
nicola

Reputation: 24480

I have to contradict myself and what I said in the comments. The .Devices object provides the needed info:

pdf()
.Devices
#[[1]]
#[1] "null device"
#[[2]]
#[1] "pdf"
#attr(,"filepath")
#[1] "Rplots.pdf"
#[[3]]
#[1] ""

The file name is stored as an attribute, as you can see from the output.

As @RichieCotton noticed, the "singular" version of the above object, .Device, gives info on just the current device (and not on the entire list), so extracting the filepath is as easy as:

attr(.Device, "filepath")
#[1] "Rplots.pdf"

Upvotes: 6

Related Questions