Rate inline r code in rmarkdown figure heading

I use RStudio and knitr to knit .Rmd to.docx

I would like to include inline code in the captions for the drawings, for example. something like the following in chunk variants:

fig.cap = "Graph nrow(data) points"

However, knitr does not evaluate this code, but simply prints an invaluable command.

Is there a way to get knitr to evaluate the r-code in the headers of the figures / tables?

+6
source share
1 answer

knitr evaluates block parameters as R code. Therefore, to include the value of a variable in the title of the picture, simply make the necessary line with paste or sprintf :

 fig.cap = paste("Graph of", nrow(data), "data points") 

Please note that this can be problematic if data is created inside this fragment (and not in the previous fragment), because by default the parameters of the piece are evaluated before the piece itself is evaluated.

To solve this problem, use the eval.after package parameter so that the fig.cap parameter is evaluated after the piece itself has been evaluated

 library(knitr) opts_knit$set(eval.after = "fig.cap") 

Here is a complete example:

 --- title: "SO" output: word_document: fig_caption: yes --- ```{r fig.cap = paste("Graph of", nrow(iris), "data points.")} plot(iris) ``` ```{r setup} library(knitr) opts_knit$set(eval.after = "fig.cap") ``` ```{r fig.cap = paste("Graph of", nrow(data2), "data points.")} data2 <- data.frame(1:10) plot(data2) ``` 

The first figure caption works even without eval.after , because the iris dataset is always available (as long as the datasets been attached). The generation of the second picture header would end without eval.after , because data2 does not exist before the last piece is processed.

+8
source

All Articles