14.8 Allow duplicate labels in code chunks (*)

By default, knitr does not allow duplicate code chunk labels in the document. Duplicate labels will result in an error when the document is knitted. This occurs most frequently when a code chunk is copied and pasted within a document. You may have seen an error message like this:

processing file: myfile.Rmd
Error in parse_block(g[-1], g[1], params.src, markdown_mode) :
  Duplicate chunk label 'cars'
Calls: <Anonymous> ... process_file -> split_file -> lapply ->
  FUN -> parse_block
Execution halted

However, there are scenarios where we may wish to allow duplicate labels. For example, if we have one parent document parent.Rmd in which we knit the child document multiple times, it will fail:

# settings
settings <- list(...)

# run once
knit_child("useful_analysis.Rmd")

# new settings
settings <- list(...)

# run again
knit_child("useful_analysis.Rmd")

In this scenario, we can allow duplicate labels by setting this global option in R before the child document is knitted:

options(knitr.duplicate.label = "allow")

If you want to allow duplicate labels in the main document instead of the child document, you have to set this option before knitr::knit() is called. One possible way to achieve that is to set the option in your ~/.Rprofile file (see the help page ?Rprofile for more information).

You should set this option with caution. As with most error messages, they are there for a reason. Allowing duplicate chunks can create silent problems with figures and cross references. For example, in theory, if two code chunks have the same label and both chunks generate plots, their plot files will overwrite each other (without error or warning messages), because the filenames of plots are determined by the chunk labels. With the option knitr.duplicate.label = "allow", knitr will silently change the duplicate labels by adding numeric suffixes. For example, for the two code chunks:

```{r, test}
plot(1:10)
```

```{r, test}
plot(10:1)
```

The second label will be silently changed to test-1. This may avoid overwriting the plot from the chunk with the label test, but it also makes the chunk label unpredictable, so you may have difficulties in cross-referencing figures (see Section 4.7), because the cross references are also based on chunk labels.