Rmarkdown Chunk name from variable

How can I use a variable as a fragment name? I have a child document that is invoked several times, and I need to advance the block labels so that I can also cross-reference them.

Something like that:

child.Rmd

```{r } if(!exists('existing')) existing <- 0 existing = existing + 1 myChunk <- sprintf("myChunk-%s",existing) ``` ## Analysis Routine `r existing` ```{r myChunk,echo = FALSE} #DO SOMETHING, LIKE PLOT ``` 

master.Rmd

 # Analysis Routines Analysis for this can be seen in figures \ref{myChunk-1}, \ref{myChunk-2} and \ref{myChunk-3} ```{r child = 'child.Rmd'} ``` ```{r child = 'child.Rmd'} ``` ```{r child = 'child.Rmd'} ``` 

CHANGE POTENTIAL DECISION

Here is one possible workaround inspired by SQL injection of all things ...

child.Rmd

 ```{r } if(!exists('existing')) existing <- 0 existing = existing + 1 myChunk <- sprintf("myChunk-%s",existing) ``` ## Analysis Routine `r existing` ```{r myChunk,echo = FALSE,fig.cap=sprintf("The Caption}\\label{%s",myChunk)} #DO SOMETHING, LIKE PLOT ``` 
+5
source share
1 answer

We suggest pre-writing the Rmd file to another Rmd file before knitting and rendering as follows

master.Rmd:

 # Analysis Routines Analysis for this can be seen in figures `r paste(paste0("\\ref{", CHUNK_NAME, 1:NUM_CHUNKS, "}"), collapse=", ")` @@@ rmdTxt <- unlist(lapply(1:NUM_CHUNKS, function(n) { c(paste0("## Analysis Routine ", n), paste0("```{r ",CHUNK_NAME, n, ", child = 'child.Rmd'}"), "```") })) writeLines(rmdTxt) @@@ 

child.Rmd:

 ```{r,echo = FALSE} plot(rnorm(100)) ``` 

Knit and make Rmd:

 devtools::install_github("chinsoon12/PreKnitPostHTMLRender") library(PreKnitPostHTMLRender) #requires version >= 0.1.1 NUM_CHUNKS <- 5 CHUNK_NAME <- "myChunk-" preknit_knit_render_postrender("master.Rmd", "test__test.html") 

Hope this helps. Hooray!

+1
source

All Articles