Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rmarkdown Chunk Name from Variable

Tags:

r

r-markdown

How can I use a variable as the chunk name? I have a child document which gets called a number of times, and I need to advance the chunk labels in such a manner than I can also cross reference them.

Something like this:

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'}
```

EDIT POTENTIAL SOLUTION

Here is one potential 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
```
like image 747
Nicholas Hamilton Avatar asked Jun 08 '16 13:06

Nicholas Hamilton


1 Answers

A suggestion to preknit the Rmd file into another Rmd file before knitting&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))
```

To knit & render the 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 it helps. Cheers!

like image 155
chinsoon12 Avatar answered Oct 21 '22 02:10

chinsoon12