title: R knitr: Possible to programmatically modify chunk labels?
body: <p>I'm trying to use knitr to generate a report that performs the same set of analyses on different subsets of a data set. The project contains two Rmd files: the first file is a master document that sets up the workspace and the document, the second file only contains chunks that perform the analyses and generates associated figures.</p>
  
  <p>What I would like to do is knit the master file, which would then call the second file for each data subset and include the results in a single document. Below is a simple example.</p>
  
  <p>Master document:</p>
  
  <pre><code># My report
  
  ```{r}
  library(iterators)
  data(mtcars)
  ```
  
  ```{r create-iterator}
  cyl.i &lt;- iter(unique(mtcars$cyl))
  ```
  
  ## Generate report for each level of cylinder variable
  ```{r cyl4-report, child='analysis-template.Rmd'}
  ```
  
  ```{r cyl6-report, child='analysis-template.Rmd'}
  ```
  
  ```{r cyl8-report, child='analysis-template.Rmd'}
  ```
  </code></pre>
  
  <p>analysis-template.Rmd:</p>
  
  <pre><code>```{r, results='asis'}
  cur.cyl &lt;- nextElem(cyl.i)
  cat("###", cur.cyl)
  ```
  
  ```{r mpg-histogram}
  hist(mtcars$mpg[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders"))
  ```
  
  ```{r weight-histogam}
  hist(mtcars$wt[mtcars$cyl == cur.cyl], main = paste(cur.cyl, "cylinders"))
  ```
  </code></pre>
  
  <p>The problem is knitr does not allow for non-unique chunk labels, so knitting fails when <code>analysis-template.Rmd</code> is called the second time. This problem could be avoided by leaving the chunks unnamed since unique labels would then be automatically generated. This isn't ideal, however, because I'd like to use the chunk labels to create informative filenames for the exported plots.</p>
  
  <hr>
  
  <p>A potential solution would be using a simple function that appends the current cylinder to the chunk label:</p>
  
  <pre><code>```r{paste('cur-label', cyl, sep = "-")}
  ```
  </code></pre>
  
  <p>But it doesn't appear that knitr will evaluate an expression in the chunk label position.</p>
  
  <hr>
  
  <p>I also tried using a custom <a href="http://yihui.name/knitr/hooks#chunk_hooks">chunk hook</a> that modified the current chunk's label: </p>
  
  <pre><code>knit_hooks$set(cyl.suffix = function(before, options, envir) {
      if (before) options$label &lt;- "new-label"
  })
  </code></pre>
  
  <p>But changing the chunk label didn't affect the filenames for generated plots, so I didn't think knitr was utilizing the new label.</p>
  
  <hr>
  
  <p>Any ideas on how to change chunk labels so the same child document can be called multiple times? Or perhaps an alternative strategy to accomplish this? </p>