When storing plots in a pdf R generates a temporary file (e.g. /tmp/RtmpFKQqjI/pdf317d27df81a0) for each plot. After drawing many plots into a pdf my /tmp partition runs out of memory and R stops working (my desktop also freezes).
Little code example:
for (i in 1:10) {
pdf(file=paste(i, ".pdf", sep=""))
plot(1:10)
dev.off()
}
list.files(path=tempdir(), pattern="^pdf.", full.names=TRUE)
# [1] "/tmp/RtmpFKQqjI/pdf317d27df81a0" "/tmp/RtmpFKQqjI/pdf317d28ed0612"
# [3] "/tmp/RtmpFKQqjI/pdf317d295c2453" "/tmp/RtmpFKQqjI/pdf317d304bb025"
# [5] "/tmp/RtmpFKQqjI/pdf317d3332d7fe" "/tmp/RtmpFKQqjI/pdf317d3921428f"
# [7] "/tmp/RtmpFKQqjI/pdf317d4cf812ca" "/tmp/RtmpFKQqjI/pdf317d5082bebe"
# [9] "/tmp/RtmpFKQqjI/pdf317d560d326" "/tmp/RtmpFKQqjI/pdf317d674b25ea"
(Same results for pdf(file="Rplots%03d.pdf"); for (i in 1:10) { ... }; dev.off().)
Why doesn’t R remove this temporary files after calling dev.off()?
As a workaround I add the following line after each dev.off():
unlink(list.files(path=tempdir(), pattern="^pdf.", full.names=TRUE))
Is there a better way?
I tend to agree with @stark that this is a (minor) bug in R’s
pdfdevice implementation.One workaround is to instead use the
cairo_pdfdevice, which produces essentially identical pdfs but does not leave extra files lying around in the temp directory.