3

This is a follow-up question about this answer. I have set the knitr chunk options to output a png and pdf version of plots in a folder, as well as use the pngs in the knitted report.

However, I'd only like to keep the pdf version of the figure and discard the png file. Is there a knitr-equivalent of on.exit() to clean up the pngs after knitting? Or an option I overlooked?

With the rmarkdown document below, how do I automatically clean up the png version of the plot after knitting? (Or not produce it as a standalone file in the first place)

---
title: "Untitled"
author: "Me"
date: "21/10/2021"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  dev = c("png", "pdf"),
  fig.path = here::here(
    "figures",
    gsub("\\.Rmd$", "\\\\", basename(knitr::current_input()))
  )
)
```

```{r my_plot}
library(ggplot2)

ggplot(mpg, aes(displ, hwy)) +
  geom_point()
```
teunbrand
  • 33,645
  • 4
  • 37
  • 63
  • I might misunderstand the question, but if you don't want to create png files, why do you set `dev = c("png","pdf")`? – tjebo Oct 21 '21 at 11:59
  • 2
    I want the output document to contain png images, but not pdf images. I want the pdf files as a side-effect of knitting the document for a collaborator who likes them to be available. I hope that makes sense. – teunbrand Oct 21 '21 at 14:11

1 Answers1

0

That is not exactly what you are looking for, but manually removing eval=FALSE from the following chunk, deletes the wanted files:

```{r eval=FALSE, include=FALSE}
fList <-  dir("figures")
fList <- fList[stringr::str_detect(fList,"\\.png$")]
file.remove(paste0("figures/",fList))
```
PaulS
  • 21,159
  • 2
  • 9
  • 26