R markdown knitting errors with repeated chunks

Viewed 24

I included a check to install an R package if it's not already installed by the following syntax:

```{r setup-packages, results=FALSE, message=FALSE, warning=FALSE}
if(! require("readxl")) install.packages("readxl")
```

which returns this error:

processing file: Testing.Rmd
Error in parse_block(g[-1], g[1], params.src, markdown_mode) : 

  Duplicate chunk label 'setup-packages', which has been used for the chunk:

if(! require("readxl")) install.packages("readxl")

Calls: <Anonymous> ... process_file -> split_file -> lapply -> FUN -> parse_block

Execution halted

The knitting works if I change {r setup-packages, results=FALSE, message=FALSE, warning=FALSE} to {r}.

I want to reuse this chunk {r setup-packages, results=FALSE, message=FALSE, warning=FALSE} for each package but it only works once. Can someone explain or provide a solution to make it work with other packages?

1 Answers

knitr is erroring due to the reuse of a chunk name. Each chunk must be unnamed, as you found works with just {r}, or uniquely named.

You can fix it in any of these ways:

  1. Put the lines for each of your package checks in a single chunk.

  2. Rename each chunk to have a unique name, like setup-packages-readxl.

  3. Set the option options(knitr.duplicate.label = "allow") in your Rprofile, though this is not a recommended use of this power according to the knitr documentation.

Related