3

When compiling knitr reports, I would like to automatically change the name of the files (eg label-1.pdf) saved on the disc to include the automated numbering of the figures captions (eg Figure-054.pdf).

Example :

---
title: "Test"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,  fig.path = 'Figures/', fig.cap = '  ', fig.pos = "H")
```

```{r}
summary(cars)
```

```{r cars}
plot(cars)
```

```{r, fig.cap = 'pressure'}
plot(pressure)
```

```{r}
summary(iris)
```

```{r}
plot(iris)
plot(iris[,1] ~ iris[,5])
```

I obtain 4 file names

cars-1.pdf
unnamed-chunk-2-1.pdf
unnamed-chunk-4-1.pdf
unnamed-chunk-4-2.pdf

I would like to obtain instead something like this (i.e. corresponding to the numbering in the pdf report) :

Figure-001.pdf
Figure-002.pdf
Figure-003.pdf
Figure-004.pdf

I know that the figures names can be changed with fig.process knitr option. But I don't know how I can capture the automated figure number.

Gilles San Martin
  • 4,224
  • 1
  • 18
  • 31

1 Answers1

0

I have part of the answer.

You have to name your chunks accordingly:

---
title: "Test"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,  fig.path = 'Figures/', fig.cap = '  ', fig.pos = "H")
```

```{r}
summary(cars)
```

```{r Figure1}
plot(cars)
```

```{r Figure2, fig.cap = 'pressure'}
plot(pressure)
```

```{r }
summary(iris)
```

```{r Figure3}
plot(iris)

```

```{r Figure4}
plot(iris[,1] ~ iris[,5])
```

Ideally, create one figure per chunk. I don't know yet how to get rid of the extra numbers knitr adds at the end of the chunk name.

FabianUx
  • 32
  • 5
  • Thanks @FabianCid but this is not a viable solution. At each time you insert a new graph or change the order of the graphs you must re-edit all chunk labels by hand... – Gilles San Martin Sep 07 '17 at 00:29
  • I think it is viable, but not robust. To make it more robust, you can use [This answer](http://stackoverflow.com/questions/12095113/r-knitr-possible-to-programmatically-modify-chunk-labels) – FabianUx Sep 07 '17 at 00:57